zend-framework2zend-paginator

ZF2 paginator performance with fetchAll without limit?


Most of cases in ZF2 I would do a paginator like this:

public function fetchAll()
{
 $resultSet = $this->tableGateway->select();
 return $resultSet;
}

$iteratorAdapter = new \Zend\Paginator\Adapter\Iterator($this->getSampleTable()->fetchAll());
$paginator = new \Zend\Paginator\Paginator($iteratorAdapter);

The problem of this aproch is that It is not limiting the query result, and fetchAll returns all the results (producing big trafic between db and php).

In pure php I would do a pagination like this:

$PAGE_NUM = $_GET['page_num'];
$result_num = mysq_query("SELECT * FROM table WHERE some condition");
$result = mysq_query("SELECT * FROM table WHERE some condition LIMIT $PAGE_NUM, 20");
echo do_paginator($result_num, 20, $PAGE_NUM);//THIS JUST MAKE THE CLASSIC < 1 2 3 4 5 >

The advantage of this is that I fetch from the DB only the data I need in the pagination thanks to LIMIT option in mysql. This is translate in good performance on query that returns too much records.

Can I use the ZF2 paginator with a effective limit to the results, or I need to make my own paginator?


Solution

  • Use the Zend\Paginator\Adapter\DbSelect adapter instead, it does exactly what you're asking for, applying limit and offset to the query you give it to begin with, and just fetching those records.

    Additionally this adapter does not fetch all records from the database in order to count them. Instead, the adapter manipulates the original query to produce a corresponding COUNT query. Paginator then executes that COUNT query to get the number of rows. This does require an extra round-trip to the database, but this is many times faster than fetching an entire result set and using count(), especially with large collections of data.