How to use Zend_Paginator correctly

    My friend wrote an article in the sandbox that turned out to be useful to me (and not only), but was deleted after 7 days. With his permission, I bring it below. If anyone will find it useful, he asks to send him an invite to alxsad@gmail.com.

    Hello to all fans of the Zend Framework. I want to explain how to use the Zend_Paginator component correctly. I very often saw how some programmers work poorly with it. Let's look at the code below:

    $pages = new Model_Pages();
    $paginator = Zend_Paginator::factory($pages->getRows());
    $paginator->setItemCountPerPage(1);
    $paginator->setPageRange(1);
    $paginator->setCurrentPageNumber($this->getRequest()->getParam('page', 1));
    Zend_Paginator::setDefaultScrollingStyle('Sliding');
    $this->view->pages = $paginator;
    $paginator->setView($this->view);
    Zend_View_Helper_PaginationControl::setDefaultViewPartial('paginator.phtml');
    $this->view->paginator = $paginator;

    * This source code was highlighted with Source Code Highlighter.


    I met this code on so many blogs, and even, if I’m not mistaken, in the Zend Framework manual itself. Let’s now look at the query that we get as a result:

    image

    See? The problem is that people immediately take ALL records from the database, and then they select the right ones from them. This is a huge mistake. Therefore, we read how to do it
    right.

    We add this method to the table model:

    public function getPaginatorRows ($pageNumber = 1)
    {
      $paginator = new Zend_Paginator(new Zend_Paginator_Adapter_DbSelect($this->select()));
      $paginator->setCurrentPageNumber($pageNumber);
      $paginator->setItemCountPerPage(1);
      $paginator->setPageRange(1);
      return $paginator;
    }

    * This source code was highlighted with Source Code Highlighter.


    and then in the controller we call it:

    $pages = new Model_Pages();
    $this->view->pages = $pages->getPaginatorRows((int) $this->getRequest()->getParam('page', 1));

    * This source code was highlighted with Source Code Highlighter.


    Voila!

    image

    Also popular now: