mrkrstphr's blog

twitter github

Using Doctrine Paginator with Zend Framework 2 Paginator

Posted on 26 Feb 2013

So Doctrine has a Paginator that uses DQL and Zend Framework has a Paginator for paginating whatever the eff. So which do you use, what do you do? Answer: smash them together!

I created a super simple Adapter for Zend\Paginator that uses the Doctrine\ORM\Tools\Pagination\Paginator class:


namespace Application\Paginator;

use Zend\Paginator\Adapter\AdapterInterface;
use Doctrine\ORM\Tools\Pagination\Paginator;

class DoctrinePaginatorAdapter implements AdapterInterface {
  protected $paginator = null;
  protected $count = null;

  public function __construct(Paginator $paginator) {
    $this->paginator = $paginator;
    $this->count = count($paginator);

  public function getItems($offset, $itemCountPerPage) {
    return $this->paginator->getIterator();

  public function count() {
    return $this->count;

Now I have a method in my Repository that gives me a Doctrine\ORM\Tools\Pagination\Paginator:


public function getPaginator($offset = 0, $limit = 20) {
  $dql = 'SELECT e FROM Application\\Domain\\Model\\Entity e ' .
    'ORDER BY e.column ASC';

  $query = $this->manager->createQuery($dql)

  $paginator = new Paginator($query);

  return $paginator;

Finally, in my controller, I call this method, pass it off to my DoctrinePaginatorAdapter, then hand that off to Zend\Paginator. Boom!


public function indexAction() {
  $page = $this->params('page');
  $max = 20;

  $results = $this->repository->getPaginator(($page - 1) * 20, $max);

  $adapter = new DoctrinePaginatorAdapter($results);
  $paginator = new Paginator($adapter);

  return array(
      'paginator' => $paginator

And just like that, I have pagination marrying Zend Framework and Doctrine’s pagination wizardry. So simple, even a caveman could do it!TM


The Clean Architecture in PHP

I've written a book on the Clean Architecture in PHP, which covers how to cleanly organize and decouple your code in a way that prepares it to survive and be easy to maintain for the long term.

Check it out!