The new Zend Framework 1.6 release candidate includes a Zend_Paginator class, which is an excellent thing to have around because I know I’ve re-invented that wheel on every site I’ve developed. My only criticism of the new Zend_Paginator is it offers a daunting amount of possibilities.

To that end, here’s a quick cheat sheet to get things up and running:

First, we need to establish the data source and initialize the paginator

class EventController {
    public function listAction() {
        //get an array of events
        $arrEvents = Core::Event::fetch_by_filter(array('link' => array('child' => $objCharacter), 'eventExpire' => time()));
       //initialize the paginator using the handy factory method..
        $paginator = Zend_Paginator::factory($arrEvents);
        //tell the paginator which page we're on
	$paginator->setCurrentPageNumber($this->_getParam('page'));
        //pass the paginator into the view
	$this->view->paginator = $paginator;
    }
}

Then we need to put the paginator to use:

< ?php if (count($this->paginator)): ?>
    < ?php foreach ($this->paginator as $item): ?>
  • < ?php echo $item->title; ?>

    < ?php echo $item->message ?>
  • < ?php endforeach; ?>
< ?php endif; ?> < ?= $this->paginationControl($this->paginator, 'Sliding', 'pagination_control.phtml'); ?>

Then, we need to create the pagination control (surely this could be a view helper?). The manual page for Zend_Paginator provides a number of different examples. I’ve chosen to use the sliding control just for aesthetic purposes:

< ?php if ($this->pageCount): ?>
< ?= $this->firstItemNumber; ?> - < ?= $this->lastItemNumber; ?> of < ?= $this->totalItemCount; ?> <a href="< ?= $this->url(array('page' => $this->first)); ?>">First</a> | < ?php if (isset($this->previous)): ?> <a href="< ?= $this->url(array('page' => $this->previous)); ?>">< Previous</a> | < ?php else: ?> <span class="disabled">< Previous</span> | < ?php endif; ?> < ?php if (isset($this->next)): ?> <a href="< ?= $this->url(array('page' => $this->next)); ?>">Next ></a> | < ?php else: ?> <span class="disabled">Next ></span> | < ?php endif; ?> <a href="< ?= $this->url(array('page' => $this->last)); ?>">Last</a>
< ?php endif; ?>

Finally, a quick little Zend_Router route to pretty up the URL:

$router->addRoute('event_list', new Zend_Controller_Router_Route('event/list/:page', array('controller' => 'event', 'action' => 'list')));

Now, when you navigate to /event/list/1, you have a paginated list (unstyled):