6. Collections

Collections do exactly the same thing as models except it manipulates multiple models instead. Collections can be iterable and access as arrays as well. Collections only hold model objects so if you wanted to use your own extended model, you would need to call setModel('Your_Model').

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

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

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

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

$collection->save('user', $database);	//save to 'user' table in database
										//only relavent columns will be saved
										//for all rows

Some other utility methods not covered by th above examples are date formating and copying from one column to another. Figure 16, show how we would go about doing these things.

Firgure 16. Utility methods
$collection->formatTime('post_created', 'F d, y g:ia'); //formats a date column
$collection->copy('post_user', 'user_id'); 				//for each row, copy the value of post_user to the user_id column
$collection->cut(1); 									//remove the row with the index of 1, reindexes all the rows
$collection->count();									//returns the number of rows
$collection->add(array('post_title' => 'Hi'));			//adds a new row
$collection->get();										//returns a table array (no objects)

© 2012 Openovate Labs. All rights reserved.