Benjamin Tigano Developer at Large


Pagination with Zend Framework

I'm currently working on the photo gallery portion of a website for a constructions company that sells and installs fiberglass pools. Obviously, having images of gorgeous pools can help convince a potential buyer (especially when these particular pools are like the ones you see on MTV Cribs), so the gallery needs to be advanced - built from the ground up. I've been given hundreds of different galleries to post on the site, each with dozens of pictures per album. That creates the need to paginate. Like the rest of the site, I'm using components of Zend Framework. I haven't yet needed to paginate anything using ZF, so I figured I'd share my experience testing out what they've got to offer.

// first, include the files we'll need
require 'Zend/Paginator.php';
require 'Zend/Paginator/Adapter/Array.php';

$array = array('1', '2', '3', '4', '5', '6', '7'); // array of data to paginate
$paginator = new Zend_Paginator(new Zend_Paginator_Adapter_Array($array)); // create the paginator
$paginator->setCurrentPageNumber((int)($_GET['page'])); // get the current page number that we're on
$paginator->setItemCountPerPage(2); // only show two per page

// these are the variables we'll likely need in order to create the "prev/next page" links
$currentPageNumber = $paginator->getCurrentPageNumber();
$itemCountPerPage = $paginator->getItemCountPerPage();
$totalItemCount = $paginator->getTotalItemCount();
$totalPageCount = $paginator->count();

Now that we've got the paginator set-up and loaded with our data, we can now output the HTML for the prev/next links.

// if not page 1, show the "prev" page link
<!--?php if ($currentPageNumber != 1):?-->
<a href="/?page=<?php echo $currentPageNumber - 1 ?>">Prev</a>
<!--?php endif; ?--></pre>
// if not the last page, show the "next" page link
<!--?php if ($currentPageNumber < $totalPageCount):?-->
   <a href="/?page=<?php echo $currentPageNumber + 1 ?>">Next</a>
<!--?php endif; ?-->

// display each item on the current page in the paginator
<!--?php if (count($paginator)): ?--></pre>
<!--?php endif; ?-->

You'll likely want to display the results differently, but I just wanted to show a quick example since you'll have to show the prev/next links and traverse through each pages items regardless of your implementation.

Got comments or questions? Leave a message below.


Fork me on GitHub
Comments (0) Trackbacks (0)

Sorry, the comment form is closed at this time.

No trackbacks yet.