Search code examples
zend-frameworkmodelcontrollerzend-db-table

Zend_Db_Table and db->select in controller or model


I'm a little bit confused with Zend. Many examples show the usage of Zend_db_Table in the controller. But from what I've learn about MVC, anything about DB should be in the model. Now that Zend is created and maintain by PHP team, I really don't know what to think, so I follow the rule without asking.

Here is an example of the kind of code I put in the controller for now.

Thanks to anyone who could clarify my doubt.

$filter = $this->_getParam('filter', array());
$order_by = $this->_getParam('order_by', 'last_name');
$order = $this->_getParam('order', 'ASC');

// Select
$db = Zend_Db_Table::getDefaultAdapter();
$select = $db->select('*')->from('contact_address');

// Filter / Where
$where = array();
if(isset($filter['id']) AND $filter['id'] != ""){                                   $select->where('id = ?' , $filter['id']); }
if(isset($filter['title']) AND $filter['title'] != ""){                             $select->where('CONCAT(first_name, " ", last_name) LIKE ?', $filter['title'] . '%'); }
if(isset($filter['phone']) AND preg_match_all('/\d/', $filter['phone'], $matches)){ $select->where('phone LIKE ?', implode('', $matches[0]) . '%'); }
if(isset($filter['email']) AND $filter['email'] != ""){                             $select->where('email LIKE ?', $filter['email'] . '%'); }
if(isset($filter['published']) AND $filter['published'] != ""){                     $select->where('published = ?', $filter['published']); }
else{                                                                               $select->where('published >= 0'); }

// Order
$select->order($order_by . ' ' . $order);
$select->order('last_name ASC');

// Pagination
$paginator = Zend_Paginator::factory($select);
$paginator->setCurrentPageNumber($this->_getParam('page', 1));
$paginator->setItemCountPerPage($_SESSION['LIMIT_PER_PAGE']);

Solution

  • Here is a nice slideshow about the model part in Zend from a zend guru http://www.slideshare.net/weierophinney/architecting-your-models. It took me a while to fully understand how Zend sees MVC. We went even one step further and introduced a service layer for inter module communication How to implement service layer in Zend Framework?