-
Notifications
You must be signed in to change notification settings - Fork 12
5.7. Collection
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.
use Cradle\Data\Collection;
$collection = new Collection;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';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 modeleach - 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']); //--> Modelset - Sets the collection
$collection->set([
['foo' => 'bar'],
['foo' => 'zoo']
]);2.B. Reference: Validation Types
2.D. Reference: Indexes & Relations
3.A. Reference: Cradle on Shared Hosts
3.B. Reference: Command Line Tools
3.C. Reference: Architecture Recommendations
4.4. Intro to Handlebars Templating
4.B. Reference: Handlebars Helpers
4.C. Reference: Doon Interfaces
4.D. Reference: Global Package Methods