Friday, March 21, 2008

Perfect PHP Pagination

Pagination is a topic that has been done to death -- dozens of
articles and reference classes can be found for the management
of result sets ... however (and you knew there was a "however"
coming there, didn't you?) I've always been disgruntled with the
current offerings to date. In this article I offer an improved
solution.
Some pagination classes require parameters, such as a database resource
and an SQL string or two, to be passed to the constructor. Classes that
utilize this approach are lacking in flexibility - what if you require a
different formatting of page numbers at the top and bottom of your pages,
for example? Do you then have to modify some output function, or subclass the entire class, just to override
that one method? These potential "solutions" are restrictive and don't encourage code reuse.
This tutorial is an attempt to further abstract a class for managing result pagination, thereby removing its
dependencies on database connections and SQL queries. The approach I'll discuss provides a measure of
flexibility, allowing the developer to create his or her very own page layouts, and simply register them with
the class through the use of an object oriented design pattern known as the Strategy Design Pattern.
What Is the Strategy Design Pattern?
Consider the following: you have on your site a handful of web pages for which the results of a query are
paged. Your site uses a function or class that handles the retrieval of your results and the publishing of your
paged links.
This is all well and good until you decide to change the layout of the paged links on one (or all) of the pages.
In doing so, you're most likely going to have to modify the method to which this responsibility was
delegated.
Perfect PHP Pagination
Perfect PHP Pagination http://www.sitepoint.com/print/perfect-php-pagination
2 of 8 2/17/2008 9:44 PM
A better solution would be to create as many layouts as you like, and dynamically choose the one you desire
at runtime. The Strategy Design Pattern allows you to do this. In a nutshell, the Strategy Design Pattern is
an object oriented design pattern used by a class that wants to swap behavior at run time.
Using the polymorphic capabilities of [1], a container class (such as the Paginated class that we'll build
in this article) uses an object that implements an interface, and defines concrete implementations for the
methods defined in that interface.
While an interface cannot be instantiated, it can reference implementing classes. So when we create a new
layout, we can let the strategy or interface within the container (the Paginated class) reference the layouts
dynamically at runtime. Calls that produce the paged links will therefore produce a page that's rendered
with the currently referenced layout.
Required Files
As I mentioned, this tutorial is not about the mechanics of how results are paged, but how to use an
interface to implement this logic while retaining flexibility. I've provided as a starting point a class that
contains functionality for registering primitive [2] or objects - the Paginated class -- as well as an
interface that all of our page layouts must implement (PageLayout) and an implementation for a page
layout (DoubleBarLayout). And all the code we'll use in the article is available for download [3].
A Basic Example
The following examples use an array of strings. Here's my data set:
Andrew
Bernard
Castello
Dennis
Ernie
Frank
Greg
Henry
Isac
Jax
Kester
Leonard
Matthew
Nigel
Oscar
However, this code could easily be extended to use an array of integers, characters, or other objects that
have been fetched from a previous database call.
Here's how we'd use the Paginated class:
PHP
arrays
Perfect PHP Pagination http://www.sitepoint.com/print/perfect-php-pagination
3 of 8 2/17/2008 9:44 PM
require_once "Paginated.php";
//create an array of names in alphabetic order
$names = array("Andrew", "Bernard", "Castello", "Dennis", "Ernie",
Frank", Greg", "Henry", "Isac", "Jax", "Kester", "Leonard",
"Matthew", "Nigel", "Oscar");
$pagedResults = new Paginated($names, 10, 1);
echo "

    ";
    while($row = $pagedResults->fetchPagedRow()) {
    echo "
  • {$row}
  • ";
    }
    echo "
";
?>
First, we include the Paginated class and register an array with the constructor. The constructor takes
three arguments, the final two of which are optional:
The first parameter is the array of items to display -- as I mentioned, these can be primitive data types
or more complex objects.
1.
The second parameter is the number of results we want to display on a page. By default, this figure is
set to ten.
2.
3. The third parameter is the current page number.
In the above example, we've used the constant 1 to specify "page 1", however you're probably going to want
to pass this as a parameter from the query string (more on this later). If an invalid page is supplied to the
constructor, the page will default to 1.
By calling the fetchPagedRow method from within the while loop, our code iterates through the array,
printing out the first ten names in the list (in this example, "Kester", "Leonard", "Matthew", "Nigel" and
"Oscar" would be omitted). These items should be included on page two, but, as the image below illustrates,
there are no links to page two yet! While Paginated will manage the access to any object registered by
the programmer, the responsibility of publishing paged links is delegated to a class that implements the
PageLayout interface.
Perfect PHP Pagination http://www.sitepoint.com/print/perfect-php-pagination
4 of 8 2/17/2008 9:44 PM
Let's add some code to display the page numbers, then we'll dig a little deeper into the interior workings and
flexibility of this class.
Create a new file with a PHP extension that contains the following code:
require_once "Paginated.php";
require_once "DoubleBarLayout.php";
//create an array of names in alphabetic order
$names = array("Andrew", "Bernard", "Castello", "Dennis", "Ernie",
"Frank", "Greg", "Henry", "Isac", "Jax", "Kester", "Leonard",
"Matthew", "Nigel", "Oscar");
$page = $_GET['page'];
$pagedResults = new Paginated($names, 10, 1);
echo "
    ";
    while($row = $pagedResults->fetchPagedRow()) {
    echo "
  • {$row}
  • ";
    }
    echo "
";
$pagedResults->setLayout(new DoubleBarLayout());
echo $pagedResults->fetchPagedNavigation();
?>
When we run the above script now, we'll see a list of the first ten names, as well as some additional
orientation information shown in the image below. Our script now displays the text "Page 1", as well as a
link to the second page that reads "next >".
Perfect PHP Pagination http://www.sitepoint.com/print/perfect-php-pagination
5 of 8 2/17/2008 9:44 PM
In the code snippet above, we've made use of a class called DoubleBarLayout, which implements the
interface PageLayout and contains an implementation of the fetchPagedLinks method. This
method takes two parameters: the Pagination object, and the query parameters that we want to attach
to the hyperlinks (if any).
The great thing about this method is that it takes advantage of PHP's polymorphic capabilities, allowing the
strategy that's currently registered to be called. It's therefore important for us to set the strategy first, before
calling the method. Setting the strategy is done via a call to the setter method setLayout, which takes as
a parameter an object that implements the PageLayout interface.
Hover over one of these links, and you'll notice that the parameter page and its value of 2 are included in the
URL page number. However, in its current state, if you click this link to the second page, the names that we
would expect to be rendered will not be displayed.
Let's see why this is the case by revisiting the constructor of Paginated.
The constructor takes three parameters:
1. the array of primitive variables or objects to be processed
2. the number of records to display
3. the page number
Because the method fetchPagedNavigation writes a query parameter, we can replace our
hardcoded value of 1 with the value held in $_GET['page']. This way, if the user manually modifies the
value in the URL to something that's invalid, Paginated will default the page number to 1. How you
choose to validate your GET parameters is up to you, though, so I won't dwell on this issue any further.
Flexibility in Page Layout Schemes
The flexibility of this class is accomplished via the PageLayout interface, which is part of the Paginated
object. The PageLayout interface can reference any object that implements it, and calls to the
Paginated method fetchPagedNavigation will cause the currently registered object to be
referenced. If you haven't used interfaces before, this may seem a little confusing, but basically the end
result is that the correct code will be called, and our results will be correctly spread over multiple pages.
Perfect PHP Pagination http://www.sitepoint.com/print/perfect-php-pagination
6 of 8 2/17/2008 9:44 PM
To implement this technique, all you need to do is create a layout strategy that implements the
PageLayout interface. Then, provide an implementation for the method fetchPagedLinks.
This method takes two parameters:
1. $parent, which is the Paginated object
2. $queryVars, which is the list of query parameters to append to the page numbers (and is optional)
There are three important points to note here:
You'll never be making direct calls to fetchPagedLinks. All methods of Paginated can be
accessed through the parent object.
1.
If you want to use your own page layouts, you must change the layout of the paginated result via calls
to setLayout.
2.
With those points in mind, let's create our own page layout! We'll call it TrailingLayout. Here's the
code:
class TrailingLayout implements PageLayout {
public function fetchPagedLinks($parent, $queryVars) {
$currentPage = $parent->getPageNumber();
$totalPages = $parent->fetchNumberPages();
$str = "";
if($totalPages >= 1) {
for($i = 1; $i <= $totalPages; $i++) {
$str .= " Page $i";
$str .= $i != $totalPages ? " | " : "";
}
}
return $str;
}
}
?>
The above class, TrailingLayout, implements the PageLayout interface, and provides
implementation for fetchPagedLinks. Remember the parameter $parent is an instance of the
Paginated object, so we can determine the current page, and the total number of pages, by making calls
to getPageNumber and fetchNumberPages, respectively.
Perfect PHP Pagination http://www.sitepoint.com/print/perfect-php-pagination
7 of 8 2/17/2008 9:44 PM
In this simple layout, once there's more than a single page, the script will loop through the array of pages,
and create a hyperlink and page number for each one. The $queryVars are also written to the href as
part of this loop; the parameter $queryVars comes in handy when we're paging the results of a search
that may have included a few parameters.
Note that the string "Page" is not a part of the queryVars, but is written by the loop that appends the
page numbers to the string.
Now let's try implementing our new layout:
require_once "Paginated.php";
//include your customized layout
require_once "TrailingLayout.php";
//create an array of names in alphabetic order. A database call could
have retrieved these items
$names = array("Andrew", "Bernard", "Castello", "Dennis", "Ernie",
"Frank", "Greg", "Henry", "Isac", "Jax", "Kester", "Leonard",
"Matthew", "Nigel", "Oscar");
$page = $_GET['page'];
$pagedResults = new Paginated($names, 10, $page);
echo "
    ";
    while($row = $pagedResults->fetchPagedRow()) {
    echo "
  • {$row}
  • ";
    }
    echo "
";
//$pagedResults->setLayout(new TrailingLayout());
echo $pagedResults->fetchPagedNavigation("&firstLetter=l");
?>
If we were to run the script above as is, we'd get the following error message:
"Fatal error: Call to a member function fetchPagedLinks() on a
non-object".
This error occurs because we haven't yet registered the strategy that we wish to use before calling
fetchPagedNavigation. To change the layout of the paged links, we pass to the setLayout
method a parameter, which can be any object that implements the PageLayout interface. In the code
from our TrailingLayout example above, uncomment the second-last line of PHP code, and refresh
your page to see the final result, shown below.
Perfect PHP Pagination http://www.sitepoint.com/print/perfect-php-pagination
8 of 8 2/17/2008 9:44 PM
The last line in that code demonstrates how the fetchPagedNavigation method can take an optional
parameter string to define the rest of the query (note the inclusion of the ampersand before the
firstLetter parameter in the URL to distinguish it from the page parameter).
Summary
In this article, I introduced the Strategy Design Pattern, which can be used to provide flexibility when you're
laying out paged links.
We saw this pattern in action through the Paginated class, which will hopefully prove useful to you when
you're displaying data across multiple pages. The class can be used to display arrays containing primitive
data types or more complex objects.
Back to SitePoint.com
[1] /glossary.php?q=P#term_1
[2] /glossary.php?q=%23#term_72
[3] http://www.sitepoint.com/examples/pagination/paginated-demo.zip

No comments: