PHP
  Home arrow PHP arrow Page 4 - Object Interaction in PHP: Introduction to Aggregation, part 3
Dev Shed Forums  
Administration  
AJAX  
Apache  
BrainDump  
DHTML  
Flash  
Java  
JavaScript  
Multimedia  
MySQL  
Oracle  
Perl  
PHP  
Practices  
Python  
Reviews  
Security  
Smartphone Development  
Style-Sheets  
Web Services  
XML  
Zend  
Zope  
Mobile Linux  
App Generation ROI  
IBM® developerWorks  
Forums Sitemap  
E-Commerce Hosting  
Linux Web Hosting  
Managed Hosting  
Small Business Hosting  
VPS Hosting  
Weekly Newsletter

 
Developer Updates  
Free Website Content 
 RSS  Articles
 RSS  Forums
 RSS  All Feeds
Write For Us Get Paid  
Request Media Kit
Contact Us  
Site Map  
Privacy Policy  
Support  
 USERNAME
 
 PASSWORD
 
 
  >>> SIGN UP!  
  Lost Password? 
Google.com  
PHP

Object Interaction in PHP: Introduction to Aggregation, part 3
By: Alejandro Gervasio
  • Search For More Articles!
  • Disclaimer
  • Author Terms
  • Rating: starstarstarstarstar / 18
    2005-06-08


    Table of Contents:
  • Object Interaction in PHP: Introduction to Aggregation, part 3
  • Moving back and forth: building a paging class
  • Refactoring the “displayRecords()” method
  • Completing the refactoring process: building the paging links

  • Rate this Article: Poor Best 
      ADD THIS ARTICLE TO:
      error-file:tidyout.log Del.ici.ous error-file:tidyout.log Digg
      error-file:tidyout.log Blink error-file:tidyout.log Simpy
      error-file:tidyout.log Google error-file:tidyout.log Spurl
      error-file:tidyout.log Y! MyWeb error-file:tidyout.log Furl
    Email Me Similar Content When Posted
    Add Developer Shed Article Feed To Your Site
    Email Article To Friend
    Print Version Of Article
    PDF Version Of Article

     
     
    ADVERTISEMENT


    Object Interaction in PHP: Introduction to Aggregation, part 3 - Completing the refactoring process: building the paging links
    ( Page 4 of 4 )

    If I could chose between the different parts of the method, I’d say that this one is the easiest to grasp. This section provides the essentials to create the paging links, as the final task to complete the refactoring process. While the technique that we’re using here to generate the links has been strongly documented in previous articles, it deserves a quick explanation.

    Since the method has generated the output containing values from database records, it creates the paging links by packaging them into a single <div> element. The code to build the links is listed below:

    $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 numbered 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 generated output
    return $this->output;

    Notice here that the use of the $page pointer is very relevant. We first check if it’s possible to create a <previous> link, determining if we’re not placed in the first page ($page>1). If this condition is true, we simply append that link to the final output, like this:

    if($page>1){
        $this->output.='<a href="'.$_SERVER['PHP_SELF'].'?
        page='.($page-1).'">&lt;&lt;Previous</a>&nbsp;';
    }

    Later, using a regular loop, we create the numbered links, as follows:

    for($i=1;$i<=$numPages;$i++){
        ($i!=$page)?$this->output.='<a href="'.$_SERVER
        ['PHP_SELF'].'?page='.$i.'">'.$i.'</a>
        &nbsp;':$this->output.=$i.'&nbsp;';
    }

    Finally, after the numbered link creation, we'll check if a <next> link is feasible of being appended. If it is, then we append it to the code and return the whole output for further processing:

    $this->output.='</div>';
    // return generated output
    return $this->output;

    Great! Didn’t I tell you that this was the easiest part of the method? At this point, the method is fully functional, since it’s scoped the two core processes involved in dynamic output generation: paged record visualization and paging link creation, using the benefits added by our friendly “MySQLConnector” object.

    As usual, if you want to take a look at the full code for this class and implement it in your own projects, here it is:

    class Pager {
        var $db; // MySQLConnector object
        var $query; // SQL query
        var $numRecs; // number of records per page
        var $output=''; // dynamic output
        function Pager(&$db,$query,$numRecs=5){
            $this->db=&$db;
            (preg_match("/^SELECT/",$query))?
            $this->query=$query:die('Invalid query '.$query);
            (is_int($numRecs)&&$numRecs>0)?
            $this->numRecs=$numRecs:die('Invalid number of 
            records');
        }
        function displayRecords($page){
        // calculate total number of records using MySQLConnector object
        if(!$totalRecs=$this->db->getNumRows
        ($this->db->performQuery($this->query))){
            die('Cannot retrieve records from database');
        }
        // calculate number of pages
        $numPages=ceil($totalRecs/$this->numRecs);
        // validate page pointer $page
        if(!preg_match("/^\d{1,2}$/",$page)
        ||$page<1||$page>$numPages){
            $page=1;
        }
        // retrieve result set using MySQLConnector object
        $this->db->performQuery($this->query.' LIMIT '.
        ($page-1)*$this->numRecs.','.$this->numRecs);
        while($rows=&$this->db->fetchRow()){
            foreach($rows as $row){
                $this->output.=$row.'&nbsp;';
                }
            $this->output.='<br />';
            }
        $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 numbered 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 generated output
        return $this->output;
        }
    }

    To Wrap Things Up...

    In this third part of the series, I’ve offered a full coverage about how Aggregation can be implemented on PHP applications, showing two classes often used in Web-related projects: a MySQL database abstraction class and a dynamic paging class, this way highlighting the necessary key concepts to translate the underlying theory in a practical usage. So, now the relevant question is: what’s next? In the final article of this four-part series, we’ll get more practical, showing a concrete example to, hopefully see in action both classes. Now that you’ve tasted the power of aggregation, go and put it to work for you!



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

       

    PHP ARTICLES

    - Implementing Factory Methods in PHP 5
    - Merging a File Split for FTP Upload using PHP
    - Getting Data from Yahoo Site Explorer Inboun...
    - Method Chaining: Adding More Selecting Metho...
    - How to Split a File During an FTP Upload Usi...
    - Expanding a Custom CodeIgniter Library with ...
    - Using the Yahoo Site Explorer Inbound Links ...
    - Building a CodeIgniter Custom Library with M...
    - Building an E-mini Trading System Using PHP ...
    - Completing the MySQL Class with Method Chain...
    - Building Dynamic Queries with Chainable Meth...
    - PHP Encryption and Decryption Methods
    - Building a MySQL Abstraction Class with Meth...
    - Completing a Sample String Processor with Me...
    - Mastering WHILE Loops for PHP and MySQL





    © 2003-2009 by Developer Shed. All rights reserved. DS Cluster 5 Hosted by Hostway
    For more Enterprise Application Development news, visit eWeek