![]() |
|
|
|||||||
| 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! |
![]() |
|
|
LinkBack | Thread Tools | Display Modes |
|
|
#1 (permalink) |
|
Elite Member
|
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:
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:
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:
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:
<?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. |
|
|
|
![]() |
| Thread Tools | |
| Display Modes | |
|
|
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 |