Skip to content
Martijn Smit edited this page Oct 7, 2018 · 4 revisions

A collection represents a group of objects. Each object in the collection is of a specific, defined type.

Generic Collection

This is a direct implementation of CollectionInterface, provided for the sake of convenience.

$collection = new \Ramsey\Collection\Collection('My\\Foo');
$collection->add(new \My\Foo());
$collection->add(new \My\Foo());

foreach ($collection as $foo) {
    // Do something with $foo
}

Typed Collection

It is preferable to subclass AbstractCollection to create your own typed collections. For example:

namespace My\Foo;

class FooCollection extends \Ramsey\Collection\AbstractCollection
{
    public function getType()
    {
        return 'My\\Foo';
    }
}

And then use it similarly to the earlier example:

$fooCollection = new \My\Foo\FooCollection();
$fooCollection->add(new \My\Foo());
$fooCollection->add(new \My\Foo());

foreach ($fooCollection as $foo) {
    // Do something with $foo
}

One benefit of this approach is that you may do type-checking and type-hinting on the collection object.

if ($collection instanceof \My\Foo\FooCollection) {
    // the collection is a collection of My\Foo objects
}

Instantiating from an array of objects

In addition to add, you can also create a Typed Collection from an array of objects.

$foos = [
  new \My\Foo(),
  new \My\Foo()
];

$fooCollection = new \My\Foo\FooCollection($foos);

Clone this wiki locally