ramsey/collection
ramsey/collection is a PHP 5.6+ collections framework for representing and manipulating collections.
This project adheres to a Contributor Code of Conduct. By participating in this project and its community, you are expected to uphold this code.
About
Much inspiration for this library came from the Java Collections Framework.
Installation
The preferred method of installation is via Packagist and Composer. Run
the following command to install the package and add it as a requirement to
your project's composer.json
:
composer require ramsey/collection
Examples
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);
Contributing
Contributions are welcome! Please read CONTRIBUTING for details.
Copyright and License
The ramsey/collection library is copyright © Ben Ramsey and licensed for use under the MIT License (MIT). Please see LICENSE for more information.