Base class for working with collections of things

Installs: 364

Dependents: 0

Watchers: 1

Language: PHP

0.3.0 2014-05-15 13:00 UTC


Base class for working with collections of things.

Build Status Total Downloads Latest Stable Version


You can either create instances of the Collection object...

$foo = new \werx\Collections\Collection;

Or create a class that extends it.

class Foo extends \werx\Collections\Collection


$foo = new Foo();

Fill the collection in the constructor.

$foo = new new \werx\Collections\Collection(['foo' => 'Foo', 'bar' => 'bar']);

Add multiple items to collection by passing an array to the set() method.

$foo = new Foo();
$foo->set(['foo' => 'Foo', 'bar' => 'bar']);

How many items in the collection?

# OR
var_dump(count($foo)); // The Collection class implements the Countable() interface.
// 2

Does the collection have a key named 'foo'? (yes)

// true

Does the collection have a key named 'x'? (no)

// false

Get the value of the key named 'foo' from the collection.

// Foo

Return default null if key doesn't exist.

// null

Set a different default value if key doesn't exist.

var_dump($foo->get('x', 'no'));
// no

Set a key/value.

$foo->set('name', 'Josh');

Add an item to the collection without a specific key.


Add an array to the collection without a specific key.

$foo->add(['name' => 'Josh', 'location' => 'Arkansas']);

Remove a key from the collection.


Get all keys in the collection.




Convert the collection to json.

// {"foo":"Foo","bar":"Bar"}

Casting the collection to a string will also return json.

var_dump((string) $foo);
// {"foo":"Foo","bar":"Bar"}

Empty the collection.



Installation of this package is easy with Composer. If you aren't familiar with the Composer Dependency Manager for PHP, you should read this first.


"require": {
    "werx/collections": "dev-master"


Unit Testing

$ vendor/bin/phpunit

Coding Standards

This library uses PHP_CodeSniffer to ensure coding standards are followed.

I have adopted the PHP FIG PSR-2 Coding Standard EXCEPT for the tabs vs spaces for indentation rule. PSR-2 says 4 spaces. I use tabs. No discussion.

To support indenting with tabs, I've defined a custom PSR-2 ruleset that extends the standard PSR-2 ruleset used by PHP_CodeSniffer. You can find this ruleset in the root of this project at PSR2Tabs.xml

Executing the codesniffer command from the root of this project to run the sniffer using these custom rules.

$ ./codesniffer