Documentation

Putting it all Together - Getting Started with Zend_Paginator

Putting it all Together

You have seen how to create a Paginator object, how to render the items on the current page, and how to render a navigation element to browse through your pages. In this section you will see how Paginator fits in with the rest of your MVC application.

In the following examples we will ignore the best practice implementation of using a Service Layer to keep the example simple and easier to understand. Once you get familiar with using Service Layers, it should be easy to see how Paginator can fit in with the best practice approach.

Lets start with the controller. The sample application is simple, and we'll just put everything in the IndexController and the IndexAction. Again, this is for demonstration purposes only. A real application should not use controllers in this manner.

  1. class IndexController extends Zend_Controller_Action
  2. {
  3.     public function indexAction()
  4.     {
  5.         // Setup pagination control view script. See the pagation control tutorial page
  6.         // for more information about this view script.
  7.         Zend_View_Helper_PaginationControl::setDefaultViewPartial('controls.phtml');
  8.  
  9.         // Fetch an already instantiated database connection from the registry
  10.         $db = Zend_Registry::get('db');
  11.  
  12.         // Create a select object which fetches blog posts, sorted decending by date of creation
  13.         $select = $db->select()->from('posts')->sort('date_created DESC');
  14.  
  15.         // Create a Paginator for the blog posts query
  16.         $paginator = Zend_Paginator::factory($select);
  17.  
  18.         // Read the current page number from the request. Default to 1 if no explicit page number is provided.
  19.         $paginator->setCurrentPageNumber($this->_getParam('page', 1));
  20.  
  21.         // Assign the Paginator object to the view
  22.         $this->view->paginator = $paginator;
  23.     }
  24. }

The following view script is the index.phtml view script for the IndexController's indexAction. The view script can be kept simple. We're assuming the use of the default ScrollingStyle.

  1. <ul>
  2. <?php
  3. // Render each the title of each post for the current page in a list-item
  4. foreach ($this->paginator as $item) {
  5.     echo '<li>' . $item->title . '</li>';
  6. }
  7. ?>
  8. </ul>
  9. <?php echo $this->paginator; ?>

Now navigate to your project's index and see Paginator in action. What we have discussed in this tutorial is just the tip of the iceberg. The reference manual and API documentation can tell you more about what you can do with Zend_Paginator.

Copyright

© 2006-2021 by Zend by Perforce. Made with by awesome contributors.

This website is built using zend-expressive and it runs on PHP 7.

Contacts