lithium\util\Collection::invoke PHP Method

invoke() public method

Handles dispatching of methods against all items in the collection.
public invoke ( string $method, array $params = [], array $options = [] ) : mixed
$method string The name of the method to call on each instance in the collection.
$params array The parameters to pass on each method call.
$options array Specifies options for how to run the given method against the object collection. The available options are: - `'collect'`: If `true`, the results of this method call will be returned wrapped in a new `Collection` object or subclass. - `'merge'`: Used primarily if the method being invoked returns an array. If set to `true`, merges all results arrays into one.
return mixed Returns either an array of the return values of the methods, or the return values wrapped in a `Collection` instance.
    public function invoke($method, array $params = array(), array $options = array())
    {
        $class = get_class($this);
        $defaults = array('merge' => false, 'collect' => false);
        $options += $defaults;
        $data = array();
        foreach ($this as $object) {
            $value = call_user_func_array(array(&$object, $method), $params);
            $options['merge'] ? $data = array_merge($data, $value) : ($data[$this->key()] = $value);
        }
        return $options['collect'] ? new $class(compact('data')) : $data;
    }

Usage Example

Example #1
0
	public function testObjectMethodDispatch() {
		$collection = new Collection();

		for ($i = 0; $i < 10; $i++) {
			$collection[] = new MockCollectionMarker();
		}
		$result = $collection->mark();
		$this->assertEqual($result, array_fill(0, 10, true));

		$result = $collection->mapArray();
		$this->assertEqual($result, array_fill(0, 10, array('foo')));

		$result = $collection->invoke('mapArray', array(), array('merge' => true));
		$this->assertEqual($result, array_fill(0, 10, 'foo'));

		$collection = new Collection(array(
			'data' => array_fill(0, 10, new MockCollectionObject())
		));
		$result = $collection->testFoo();
		$this->assertEqual($result, array_fill(0, 10, 'testFoo'));

		$result = $collection->invoke('testFoo', array(), array('collect' => true));
		$this->assertTrue($result instanceof Collection);
		$this->assertEqual($result->to('array'), array_fill(0, 10, 'testFoo'));
	}