Skip to content
Lucas Nothnagel edited this page Dec 30, 2022 · 3 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(): string
    {
        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);

Typed collection with generics support

Additionally, you can define the type your collection contains via generics annotations:

namespace My\Foo;

/**
 * @extends \Ramsey\Collection\AbstractCollection<My\Foo>
 *
 * @implements \IteratorAggregate<My\Foo>
 */
class FooCollection extends \Ramsey\Collection\AbstractCollection
{
    public function getType(): string
    {
        return 'My\\Foo';
    }
}

The @extends annotation allows tools like PhpStorm or PHPStan to understand which type your collection contains, and therefore allows for better static code analysis and code completion.

Due to some bug in PhpStorm currently it is also required to add the @implements annotation to allow type support for e.g. foreach loops. See https://github.com/ramsey/collection/issues/83