HomePHP Page 5 - Object Interaction in PHP: Introduction to Aggregation, part 2
Implementing the “MySQLConnector” class: a practical example - PHP
In this second part of his series, Alejandro Gervasio gets a little more technical with the basics of Aggregation. He begins working with a MySQL abstraction class and a useful paging class, and is starting to get into writing portable code and introducing the technique of aggregation.
Armed with the ready class, it’s rather simple to setup an example in order to see how it can be implemented. As you might guess, the following example shows a possible usage of the class:
// include MySQLConnector class require_once 'mysqlclass.php';
// instantiate a new object from MySQLConnector class $db=&new MySQLConnector('localhost','username','password','database'); // build the query $sql='SELECT name FROM table'; // perform query $db->performQuery($sql); // display results while($row=$db->fetchRow()){ // display values from a "name" table field echo $row['name'].'<br />'; }
echo 'Number total of records returned: '.$db->getNumRows();
From the above example, we can clearly see that connecting to MySQL, selecting a database, and displaying some results after performing a SELECT statement, is a breeze. Indeed, the code speaks by itself, simply because we really know what’s happening in each line. What’s more, the code is extremely portable for being easily plugged into another applications. What more can we ask for?
To Wrap It Up...
In this second part of the series, we’ve progressively developed a MySQL abstraction class, handy to manage database operations following an object-oriented approach. However, in order to implement aggregation in PHP, we need to have at hand another class, right? Well, in the next part we’ll build up a paging class, as the perfect complement for establishing the proper object interaction and show how aggregation can be used with these two functional classes.
Of course, as usual, feel free to use the above class to expand your own horizons in object-oriented programming and have some fun tweaking the code. See you in the next part!