Object Interaction in PHP: Introduction to Aggregation, part 3

In the third part of his series, Alejandro Gervasio digs a bit further into object-oriented PHP. He explains the barebones of a paging class and techniques used to aggregate a new “MySQLConnector” class.

Good to hear from you again, dear faithful reader! Welcome to the third part of my series, “Object Interaction in PHP: Introduction to Aggregation.” Have you been playing and tweaking the code for the MySQL abstraction class, presented in the second part?  I hope you did!

But, let’s get straight to the point that’s keeping our minds busy. In a progressive way, we’ve introduced the concept of Aggregation in an object-oriented environment, highlighting the immediate benefits of applying it in our applications. Besides, in a worthwhile attempt to lead directly into the development of several classes and make them interact in conjunction, we’ve completed the first half of the cake building our “MySQLConnector” class, in order to work with MySQL, this time using the power of the object-oriented paradigm.

However, it looks like the round is rather incomplete, right? Yes, you’re correct. But, don’t feel disappointed. In this third chapter of the story, we’ll expose the barebones of a paging class, as well as the techniques used to “aggregate” our brand new “MySQLConnector” class inside this structure. Definitively, working with simple yet efficient classes, gives to us the right guidelines to dig deeper in the exciting scenario of object-interaction in PHP.

So, armed with these concepts, it’s time to get our hands a bit dirty, starting out to create the paging class and establish the corresponding interaction between classes. Let’s go!

{mospagebreak title=Moving back and forth: building a paging class}

Surely, one of the most common applications we’ve seen in modern sites is a paging system. Although its use has been with us from long time ago, paging systems are a must for websites needing to expose massive amounts of data. However, here we’re not going to stop for a long while explaining the motives of why you should implement such a system. By now, our immediate goal is to show its structure and demonstrate how it can be integrated with a database abstraction class.

Through previous articles, I’ve thoroughly covered the interesting topic of displaying paginated data in websites using PHP, developing either a procedural solution or an object-oriented method. Just in case you’re not aware of, visit here to have a full review of the different solutions implemented to addressing the problem.

However, when we hopefully solved this issue by creating a “Pager” class, it originally exposed two noticeable features, worthy to consider: first, it accepted as an incoming parameter, a reference to a MySQL connection identifier, for providing database connectivity within the class structure. Second, the class was conceived to work independently, presenting its own methods to perform SQL queries and obtain result sets.

Now, we’ll refactor a bit the class code (just in case that you don’t know, Refactoring is the process to restructure code without changing its functionality), in order to make this class “aggregate” our already known “MySQLConnector” class. Sounds rather confusing? Well, let’s take a look at the skeleton of the newly defined “Pager” class, to clarify any possible inconvenience:

class Pager {
    var $db; // MySQLConnector object
    var $query; // SQL query
    var $numRecs; // number of records per page
    var $output=”; // dynamic output
    function Pager(){
        // code for parameter initialization
    }
    function displayRecords($page){
        // code for displaying records and paging links
}

If you look at the above code, probably you’re saying…Hey, I’ve seen this stuff before! Sure, you’re all right. I’ve shown this class in my previous articles dedicated to implement a paging system. But, let’s not judge the tool without first spotting the differences. Please remember that we’re refactoring the class code, so the class is still pointing its guns to display paginated data.

But, here’s where things get a lot more exciting. Notice that the class presents a $db data member. So, what’s that thing? Well, this data member directly represents a reference of a “MySQLConnector” object, that will be passed straight to the constructor, for being used to obtain paged result sets.

In other words, our “Pager” class aggregates the “MySQLConnector” object’s capacities for its own purposes. This is Aggregation in a nutshell! Isn’t it sweet and simple?

I’m okay, just got caught in the moment. But, let’s completely write the constructor method, so we can see how it incorporates the “MySQLConnector” object. Its definition looks like this:

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’);
}

As you can see, the constructor takes three parameters. The first, as you might easily guess, is a reference to an instance of the “MySQLConnector” object (notice the & ampersand operator preceding the variable name). Still with me right? Fine, the second parameters is a “SELECT” SQL statement, which will be performed against the selected database. Finally, the third parameter determines the number of records per page to be displayed in the web page. As usual, for this argument, I’ve opted to specify a default value of five records.

The code inside the method is hopefully easy to pick up. In the first place, it assigns the “MySQLConnector” object as a class data member, using the line:

$this->db=&$db;

Now, this object is available inside the class to be mercilessly exploited! Don’t you feel like this class is the bad boy of the block? Hum…but, let’s treat the rest of the parameters equally.

The query is properly validated by checking if it begins with the string “SELECT”, just employing a regular expression. Lastly, the number of records per page is verified to be a positive integer value.

That’s all about it. The constructor has happily performed the setting operations for the parameters, and its job is done. Having the “MySQLConnector” object living peacefully inside the class, we’re able to call its methods to build a dynamic output and show the paging links. That’s the task we’ve delegated to the other class method: “displayRecords()”. Join me in the next section to see how it works.

{mospagebreak title=Refactoring the “displayRecords()” method}

Width no doubt, this method stand on its shoulders the hard work of the class, since it must perform the proper SQL query against the database, retrieve the records for being displayed, and finally create the paging links. What a though work! However, due to the great capabilities that aggregation fully brings to this method, all of those tasks are performed with minor complications. This significantly reduced overload is a straight consequence of having at our disposal the methods offered by the “MySQLConnector” object.

Thus, let’s take a look at the original definition for this method, so we’re able to understand how it does its thing. Here’s our first glance at its structure, to perform the SQL query and generate the dynamic output from the database 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 />’;
  }
}

The method accepts a single parameter $page, which simply behaves as a page pointer to determine how to display the paged records and build up the corresponding paging links. Certainly, this logic has already been implemented in previous articles that cover completely paging mechanisms. In order to get a better understanding, you may want to read the previous articles for a full review of this technique.

However, let’s focus our attention now on the rest of the method’s code. The methods really need to calculate the total number of records returned by the query, to create the paging links. Remember that our “MySQLConnector” object is available inside the class? Good, because we use its own methods, that is, “getNumRows()” and “performQuery()”, to calculate the number of records and execute the SQL query. Isn’t it great? Please notice the below lines:

// calculate total number of records using MySQLConnector object
if(!$totalRecs=$this->db->getNumRows($this->db->performQuery($this->query))){
    die(‘Cannot retrieve records from database’);
}

The above code obtains the total number of records, using the methods generously offered by the MySQLConnector object. In first instance, the method perform the SQL query invoking directly to “performQuery()”, as listed below:

$this->db->performQuery($this->query)

And next, the expression is completed by calling the method “getNumRows()”, like this:

$totalRecs=$this->db->getNumRows($this->db->performQuery($this->query))

At this point, I guess you’ve grasped the underlying idea behind Aggregation. In both expressions we’re using the methods of the “MySQLConnector object (referenced as $this->db) to fit the purposes of the a “Pager” object. That’s what I’d call it a good friend!

The next section of the code validates the page pointer to make sure is an appropriate value, avoiding some possible tampering attempts directly manipulating URL’s, in the following manner:

if(!preg_match(“/^d{1,2}$/”,$page)||$page<1||$page>$numPages){
    $page=1;
}

The expression checks to see the value of the $page pointer. If its value is lesser than 1 or greater than the number of pages needed to show the whole result set, then it’s simply set to 1.

The rest of the code uses again the methods of the “MySQLConnector” object, “performQuery()” and “fetchRow()” respectively, in order to get a dynamic paged result set adding a LIMIT clause to the original query, lastly looping over the records to generate the final output:

$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 />’;
}

Notice that once the records are stored in the class property $this->output, we apply to them some kind of basic visual formatting. However, this might be quickly modified to accept a rather more polished visual presentation.

Okay, let’s hold our breath and recapitulate about what we’ve done until now. The method has already partially generated the dynamic output, by retrieving database records, using only the methods provided by the “MySQLConnector” object. Is there something pendent in our task list? Sure! We need to complete the source code, adding the section that builds the paging links. Let’s not waste more time and face properly that part.

{mospagebreak title=Completing the refactoring process: building the paging links}

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!

Google+ Comments

Google+ Comments