-
Notifications
You must be signed in to change notification settings - Fork 43
Collections
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.
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.
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();
Similarly, you can get items from the collection:
// get() method.
$banana = $fruit->get( 'banana' );
// Array syntax.
$banana = $fruit['banana'];
// Object syntax.
$banana = $fruit->banana;
// remove() method.
$fruit->remove( 'grape' );
// Array syntax.
unset( $fruit['grape'] );
// Object syntax.
unset( $fruit->grape );
// has() method.
if ( $fruit->has( 'orange' ) ) {}
// Array syntax.
if ( isset( $fruit['orange'] ) ) {}
// Object syntax.
if ( isset( $fruit->orange ) ) {}
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 );
}