In the previous part of this series here the Zend Framework database adapter was called, a query was executed and a hydration strategy for getting row data into a custom object was applied. Time to move on. The method works well for small queries but how about collecting thousends of rows in a single query? There is no point in sending that amount of objects to a view but Zend Paginator has a solution:

// controller action

// get current page ID
$pageId = $this->params()->fromRoute('page');
$view = new \Zend\View\Model\ViewModel;
$sm = $this->getServiceLocator();        
$config = $sm->get('Config');
$driver = $config['db'];

// get the select object
$select = new \Zend\Db\Sql\Select;
$resultSetPrototype = new \Zend\Db\ResultSet\ResultSet;
$customer = new \Application\Model\Customer;
$adapter = new \Zend\Db\Adapter\Adapter($driver);
$dbSelect = new \Zend\Paginator\Adapter\DbSelect;
 = $dbSelect($select,$adapter,$resultSetPrototype);
$paginator = new \Zend\Paginator\Paginator($paginatorAdapter);

 if ($pageId) {

$view->setVariable('customers', $paginator);

The actual execution of the query is now delegated to the view with a pre-set offset and limit. Customers is a Zend\Paginator\Paginator object that implements IteratorAggregate. The getItemsByPage() methods asks the adapter to return the items.

// view

foreach ($this->customers as $customer) :
/* @var $customer \Application\Model\customer */

   echo $customer->getCustomerName(); 


// handle page numbering
echo $this->paginationControl($this->customers, 'Sliding', 'pagination', array('route' => 'customer'));

Complicated? DbSelect is just another adapter for the paginator object. Another adapter is called ArrayAdapter and a similar result can be obtained by:

$customer = new \Application\Model\ustomer;
 $paginatorAdapter = new \Zend\Paginator\Adapter\ArrayAdapter(
$paginator = new Paginator($paginatorAdapter);

Another adapter called the Null adapter is intriguing:

$paginatorAdapter = new \Zend\Paginator\Adapter\Null(10);
$paginator = new Paginator($paginatorAdapter);

As suspected, it delivers 10 empty rows in the view. Just wondering how that is ever going to be handy.