C. Collection

Inside module/post make a new file called collection.php and paste Figure 11.

Figure 11. Post Collection
<?php //-->
class Post_Collection extends Eden_Sql_Collection {
	/* Constants
	/* Public Properties
	/* Protected Properties
	protected $_model		= 'Post_Model';
	protected $_table		= 'post';
	/* Private Properties
	/* Magic
	public function __construct() {
		$this->_database = Eden::i()->getActiveApp()->getDatabase();
	/* Public Methods
	public function setUserByEmail($email) {
		$user = $this->_database->getRow('user', 'user_email', $email);
		if(!$user) {
			return $this;
		return $this->setPostUser($user['user_id']);
	/* Protected Methods
	/* Private Methods

In the figure above we extend Eden_Sql_Collection and added the method setUserByEmail() which is an example of why we may want to extend Eden_Sql_Collection in the first place. This method simplifies a common routine into a method call. Figure 12 shows how we can go about using the collection class immediately.

Figure 12. Collection
	->formatTime('post_created', 'F d, Y g:ia')

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

Firgure 13. SQL 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

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

Firgure 14. 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.