Go Back   Yahoo Booters And Yahoo Tools > General > How To...

How To... Post All Your Custom Made Tutorials And Explainations here



Welcome to the VipraSys forums.

You are currently viewing our boards as a guest which gives you limited access to view most discussions and access our other features such as download links. By joining our free community you will have access to post topics, communicate privately with other members (PM), respond to polls, upload content and access many other special features. Registration is fast, simple and absolutely free so please, Register Now by clicking here!

Post New Thread  Reply
 
LinkBack Thread Tools Display Modes
Old 05-10-2008, 09:53 AM   #1 (permalink)
Elite Member
 
creamownedz's Avatar
 
Join Date: Mar 2008
Posts: 203

Thanks: 15
Thanked 140 Times in 68 Posts
Reputation: 260
creamownedz is a jewel in the roughcreamownedz is a jewel in the roughcreamownedz is a jewel in the rough
Send a message via Yahoo to creamownedz
Default Perfect PHP Pagination

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.


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 [Only registered users can see links. ], 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 [Only registered users can see links. ] 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 [Only registered users can see links. ].
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
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 "<ul>";

while($row = $pagedResults->fetchPagedRow()) {
echo "<li>{$row}</li>";
}

echo "</ul>";
?>

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:
  1. The first parameter is the array of items to display -- as I mentioned, these can be primitive data types or more complex objects.
  2. The second parameter is the number of results we want to display on a page. By default, this figure is set to ten.
  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.
[Only registered users can see links. ]
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:
<?php
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 "<ul>";

while($row = $pagedResults->fetchPagedRow()) {
echo "<li>{$row}</li>";
}

echo "</ul>";

$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 >".
[Only registered users can see links. ]
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.
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:
  1. You'll never be making direct calls to fetchPagedLinks. All methods of Paginated can be accessed through the parent object.
  2. If you want to use your own page layouts, you must change the layout of the paginated result via calls to setLayout.
With those points in mind, let's create our own page layout! We'll call it TrailingLayout. Here's the code:
<?php
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 .= " <a href=\"?page={$i}$queryVars\">Page $i</a>";
$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.
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:
<?php
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 "<ul>";

while($row = $pagedResults->fetchPagedRow()) {
echo "<li>{$row}</li>";
}

echo "</ul>";

//$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.
[Only registered users can see links. ]
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.
creamownedz is offline  
Digg this Post!Add Post to del.icio.usBookmark Post in TechnoratiFurl this Post!
Reply With Quote
Post New Thread  Reply


Thread Tools
Display Modes

Posting Rules
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts

vB code is On
Smilies are On
[IMG] code is On
HTML code is Off
Trackbacks are On
Pingbacks are On
Refbacks are On


Similar Threads
Thread Thread Starter Forum Replies Last Post
Perfect Uninstaller __BLooDsuCkeR__ Software related 27 Yesterday 09:12 PM
The PERFECT MAN ( BOW ) Mz.Nobody Chit-Chat 1 03-31-2008 07:00 PM
In A Perfect World ___4vin.k4n0___ Humour 0 03-30-2008 09:01 PM
The Perfect Beat __sare__ Trance 0 03-24-2008 03:33 AM


All times are GMT. The time now is 08:33 PM.

Page generated in 0.2247 seconds (74.30% PHP - 25.70% MySQL) with 17 queries

Powered by vBulletin®
Copyright ©2000 - 2009, Jelsoft Enterprises Ltd.
Search Engine Optimization by vBSEO 3.1.0..
vBCredits v1.4 Copyright ©2007 - 2008, PixelFX Studios
The logos and trademarks used on this site are the property of their respective owners.
We are not responsible for comments posted by our users, as they are the property of the poster.