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;
$select->from('customer');
$resultSetPrototype = new \Zend\Db\ResultSet\ResultSet;
$customer = new \Application\Model\Customer;
$resultSetPrototype->setArrayObjectPrototype($customer);
$adapter = new \Zend\Db\Adapter\Adapter($driver);
$dbSelect = new \Zend\Paginator\Adapter\DbSelect;
$paginatorAdapter 
 = $dbSelect($select,$adapter,$resultSetPrototype);
$paginator = new \Zend\Paginator\Paginator($paginatorAdapter);

$paginator->setDefaultItemCountPerPage(10);
$paginator->setPageRange(5);
 if ($pageId) {
    $paginator->setCurrentPageNumber($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(); 

endforeach;

// 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;
	$customer->setCustomerName('Moriarty');
 $paginatorAdapter = new \Zend\Paginator\Adapter\ArrayAdapter(
		array($customer)
	);
$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.

Advertisements