As I said in the section that you just read, the primary purpose of creating a visitor class was defining a model of interaction between the prior "Result" class and a data set pagination system. Obviously, this last component remains undefined as yet. Below I have listed the source code of a pagination class which I have been using frequently when I developed a series of articles aimed at discussing the pagination of result sets with PHP. Here is how this pagination class looks: // define 'Pager' class Certainly, I'm not going to discuss the logic of the class listed above, simply because it's out of the scope of this article. But it's clear to see that this class is capable of displaying paginated record sets returned by MySQL, in addition to including the so-called "page links." Now, once you have a good idea of how this paging class works, please have a look at the following fragment of code, excerpted from its "displayRecords()" method: // use visitor for obtaining number of rows in result set Here's where the real action takes place! If you examine the above code snippet, you'll realize that this "Pager" class uses the mentioned visitor object to determine the number of rows returned by a SELECT query, and based on this parameter, it displays chunks of database records. In other words, the visitor in question inspects the previous "Result" class, and retrieves one of the values required for the pagination system to display paginated results. At this stage, the link established between the classes that process data sets and paginate them respectively should be clear to you. Okay, having defined all the classes required to implement a comprehensive pagination system, allow me to put all the pieces together. The code listing below shows precisely how all the classes fit each other, after populating a sample "users" database table with some trivial data: try{ And finally, the output of the previous script is depicted by the following screen shot:
Final thoughts That covers the topic of using visitors for now. Over this series, I introduced in a friendly fashion the creation and usage of visitor objects in PHP 5. From basic examples of how to utilize these objects, to including them in more complex applications, the learning experience has been hopefully educational. Either if you're just starting to enter the arena of pattern-based programming or only refreshing some of its more relevant concepts, I hope this article has been helpful to you. See you in the next PHP tutorial!
blog comments powered by Disqus |