Home arrow PHP arrow Page 4 - Using Visitor Objects with MySQL Data Sets in PHP 5

Completing the round trip: defining the structure of a pagination class - PHP

If you’re looking for brand new material to help you expand your background in using design patterns with PHP 5, then hopefully this article will suit your needs. Welcome to the final installment of the series “Introducing Visitor Objects in PHP 5.” Composed of three chapters, this series walks you through the key points of creating and using visitor objects with PHP 5, and teaches you how to use them in the context of real-world applications.

TABLE OF CONTENTS:
  1. Using Visitor Objects with MySQL Data Sets in PHP 5
  2. Visiting database result sets: establishing an interaction between visitors and MySQL
  3. Revealing the anatomy of a visitor class: creating visitor objects
  4. Completing the round trip: defining the structure of a pagination class
By: Alejandro Gervasio
Rating: starstarstarstarstar / 9
August 16, 2006

print this article
SEARCH DEV SHED

TOOLS YOU CAN USE

advertisement

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
class Pager{
    private $db;
    private $query;
    private $numRecs;
    private $output='';
    public function __construct($db,$query,$numRecs=10){
        // validate query
        if(!preg_match("/^SELECT/",$query)){
            throw new Exception('Invalid query. Must begin with
SELECT');
        }
        $this->query=$query;
        // validate number of records per page
        if(!is_int($numRecs)||$numRecs<0){
            throw new Exception('Invalid number of records');
        }
        $this->numRecs=$numRecs;
        $this->db=$db;
    }
    public function displayRecords($page){
        // use visitor for obtaining number of rows in result set
        $resultObj=$this->db->query($this->query);
        $mysqlResultVisitor=new MySQLResultVisitor;
        $resultObj->acceptVisitor($mysqlResultVisitor);
        // calculate total number of records via Visitor object
        $totalRecs=$mysqlResultVisitor->visitMySQLResult
($resultObj);
        // calculate number of pages
        $numPages=ceil($totalRecs/$this->numRecs);
        if(!preg_match("/^d{1,2}$/",$page)
||$page<1||$page>$numPages){
            $page=1;
        }
        // get result set
        $resultObj=$this->db->query($this->query.' LIMIT '.
($page-1)*$this->numRecs.','.$this->numRecs);
        while($row=$resultObj->fetchRow()){
            foreach($row as $key=>$value){
                $this->output.=$value.' ';
            }
            $this->output.='<br />';
        }
        // create page links
        $this->output.='<div>';
        // create previous link
        if($page>1){
            $this->output.='<a href="'.$_SERVER['PHP_SELF'].'?
page='.($page-1).'">&lt;&lt;Previous</a>&nbsp;';
        }
        // create numerated links
        for($i=1;$i<=$numPages;$i++){
            ($i!=$page)?$this->output.='<a href="'.$_SERVER
['PHP_SELF'].'?page='.$i.'">'.$i.'</a>&nbsp;':$this-
>output.=$i.'&nbsp;';
        }
        // create next link
        if($page<$numPages){
            $this->output.='&nbsp;<a href="'.$_SERVER
['PHP_SELF'].'?page='.($page+1).'">Next&gt;&gt;</a>';
        }
        $this->output.='</div>';
        // return final output
        return $this->output;
    }
}

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
$resultObj=$this->db->query($this->query);
$mysqlResultVisitor=new MySQLResultVisitor;
$resultObj->acceptVisitor($mysqlResultVisitor);
// calculate total number of records via Visitor object
$totalRecs=$mysqlResultVisitor->visitMySQLResult($resultObj);

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{
    // connect to MySQL
    $db=new MySQL(array('host'=>'host','user'=>'user',
'password'=>'password','database'=>'database'));
    // paginate result set
    $pager=new Pager($db,'SELECT * FROM users',$numRecs=2);
    // display paged result set
    echo $pager->displayRecords($_GET['page']);
}
catch(Exception $e){
    echo $e->getMessage();
    exit();
}

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!



 
 
>>> More PHP Articles          >>> More By Alejandro Gervasio
 

blog comments powered by Disqus
escort Bursa Bursa escort Antalya eskort
   

PHP ARTICLES

- Hackers Compromise PHP Sites to Launch Attac...
- Red Hat, Zend Form OpenShift PaaS Alliance
- PHP IDE News
- BCD, Zend Extend PHP Partnership
- PHP FAQ Highlight
- PHP Creator Didn't Set Out to Create a Langu...
- PHP Trends Revealed in Zend Study
- PHP: Best Methods for Running Scheduled Jobs
- PHP Array Functions: array_change_key_case
- PHP array_combine Function
- PHP array_chunk Function
- PHP Closures as View Helpers: Lazy-Loading F...
- Using PHP Closures as View Helpers
- PHP File and Operating System Program Execut...
- PHP: Effects of Wrapping Code in Class Const...

Developer Shed Affiliates

 


Dev Shed Tutorial Topics: