5.7. Collections

A collection manages a list of models. Collections become useful when pairing it with a data store, JSON results, services etc. Implementing this object can be done like so.

Instantiating
use Cradle\Data\Collection;

$collection = new Collection;

5.7.1. Usage

Collections do exactly the same thing as models except it manipulates multiple models instead. Collections can be iterable and access as arrays as well.

//set user name for all rows
$collection->setUserName('Chris');

// set or get any abstract key for all rows
$collection->setAnyThing('foobar');

//collections are iterable
foreach($collection as $model) {        
    echo $model->getUserName().' ';
    echo $model['user_email'];
}

//access as array
echo $collection[0]['user_name'];
//set as array
$collection[0]['user_email'] = 'my@email.com';

5.7.2. API

A collection object mounts ArrayAccessTrait, CountableTrait, GeneratorTrait, IteratorTrait (see Data Traits) and implements 6 additional methods.

add - Appends a model to the collection

$collection->add(new Model);

cut - Removes a model in the collection given the index number and reindexes the collection.

$collection->cut(1); //removes the second model
$collection->cut('first'); //removes the first model
$collection->cut('last'); //removes the last model

each - Loops through each model in the list

$collection->each(function($model) {
    //do something
});

get - Returns the entire dataset as pure arrays

$collection->get();

getModel - Transforms an array into a model

$collection->getModel(['foo' => 'bar']); //--> Model

set - Sets the collection

$collection->set([
    ['foo' => 'bar'],
    ['foo' => 'zoo']
]);