Login

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:

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:

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:

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 objectif(!$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:

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:

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:

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:

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:

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:

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!