Zend_Paginator
I needed some pagination for a website I am building, so I took a look at Zend_Paginator. It is pretty straightforward and easy to use, especially if you are using the rest of the framework. The code below assume the class Foo extends Zend_Db_Table_Abstract, and grabs a Zend_Db_Select object from the table to pass in the constructor of Zend_Paginator. Zend_Paginator uses that select object to run 2 queries, one to determine the overall count of objects, and one to grab the rowset used on the page. This rowset is then accessed via getItemsByPage();
<?php
$foo = new Foo();
$paginator = new Zend_Paginator(new Zend_Paginator_Adapter_DbTableSelect($foo->select()));
$paginator->setCurrentPageNumber($this->_getParam(‘page’,1));
$paginator->setItemCountPerPage(‘2′);
$this->view->paginator = $paginator;
$this->view->rowset = $paginator->getItemsByPage($this->_getParam(‘page’,1));
?>
Of course, most of the time you wont be using a vanilla select statement, so your code may end up looking more like this:
<?php
$foo = new Foo();
$paginator = new Zend_Paginator(new Zend_Paginator_Adapter_DbTableSelect($foo->select()->where(‘publish = ?’,‘yes’)));
?>
I don’t like to have my logic for grabbing a rowset spread throughout my controller class and try to isolate it within the object.
<?php
$foo->getLatest(); //return rowset with custom query
?>
My Foo object also doesn’t directly extend Zend_Db_Table_Abstract. So, I contemplated creating a customized Zend_Paginator_Adapter, but opted instead to have an option on my “get” methods to return a select object instead of a rowset
<?php
$foo = new Foo();
$select = $foo->getLatest(array(‘paginator’ => true));
$paginator = new Zend_Paginator(new Zend_Paginator_Adapter_DbTableSelect($select));
?>
I’m not entirely sold on this approach yet… We’ll see how it pans out as more use cases are tested out. Is it bad that the getLatest method can return different types of objects based on an input parameter?