Skip to content
Justin Tadlock edited this page Aug 6, 2018 · 1 revision

One feature of Hybrid Core that can be useful is the Hybrid\Tools\Collection class, which allows you to create a collection of any arbitrary data.

A collection is a special type of object that can be accessed using either object syntax (e.g., $collection->property) or array syntax (e.g., $collection[$property]).

It's a simple way to store any collection of data.

Creating a new collection

There are two methods to creating a new collection.

Collection class:

$collection = new \Hybrid\Tools\Collection();

collect() function:

$collection = \Hybrid\collect();

For the purposes of this tutorial, I'll stick to using the simplified collect() class. Both return the exact same thing.

Let's build a collection of fruit objects:

$fruit = collect( [
	'banana'     => new Banana(),
	'grape'      => new Grape(),
	'watermelon' => new Watermelon()
] );

Of course, you can add collections of anything.

Adding items to the collection

You could also add items in a number of ways:

// add() method.
$fruit->add( 'grapefruit', new Grapefruit() );

// Array syntax.
$fruit['peach'] = new Peach();

// Object syntax.
$fruit->orange = new Orange();

Getting items from the collection

Similarly, you can get items from the collection:

// get() method.
$banana = $fruit->get( 'banana' );

// Array syntax.
$banana = $fruit['banana'];

// Object syntax.
$banana = $fruit->banana;

Removing items from the collection

// remove() method.
$fruit->remove( 'grape' );

// Array syntax.
unset( $fruit['grape'] );

// Object syntax.
unset( $fruit->grape );

Check if an item exists

// has() method.
if ( $fruit->has( 'orange' ) ) {}

// Array syntax.
if ( isset( $fruit['orange'] ) ) {}

// Object syntax.
if ( isset( $fruit->orange ) ) {}

Getting an array of all items

If you just want a simple array of all items in the collection, use the all() method:

foreach ( $fruit->all() as $slug => $fruit ) {

	var_dump( $fruit );
}