Home arrow PHP arrow Page 4 - Object Interaction in PHP: Introduction to Composition, conclusion

Assembling the whole picture: putting the classes to work - PHP

In the first article of this series, the concept of composition in object-oriented programming was explained, and illustrated with an example that implemented composition using two simple classes. In this article, we will create a MySQL database wrapping class that uses the concept of composition.

TABLE OF CONTENTS:
  1. Object Interaction in PHP: Introduction to Composition, conclusion
  2. Composition in a practical sense: building a MySQL wrapping class
  3. The other side of composition: the “Result” class
  4. Assembling the whole picture: putting the classes to work
By: Alejandro Gervasio
Rating: starstarstarstarstar / 16
July 18, 2005

print this article
SEARCH DEV SHED

TOOLS YOU CAN USE

advertisement

Having explained in detail the features of each class, it would be pretty didactical to show how we can take advantage of their abilities, emphasizing strongly the aspects inherent to Web-related tasks. Therefore, let’s start out by demonstrating the way we can connect to MySQL and retrieve some database records. The code is the following:

// include class files

require_once 'mysqlclass.php';

require_once 'resultclass.php';

// instantiate a MySQLConnector object

$options=array('host'=>'localhost','user'=>'user','password'=>'password',
'database'=>'articles');

$db=&new MySQLConnector($options);

// build query

$sql='SELECT name,site FROM articles';

// instantiate a resultSet object

$result=$db->performQuery($sql);

// display results

while($row=$result->fetchRow()){

            echo $row['name'].'&nbsp;'.$row['site'].'<br />';

}

// display total number of records

echo 'Total number of articles : '.$result->countRows(). '<br />';

In the above snippet, we’ve included the class files. Then, we’ve instantiated a “MySQLConnector” object and performed the connection to the server, passing the proper parameters, in this case selecting a sample database.

Once the connection is established, we build a simple query to get some records from an “articles” database table. Notice the usage of the “fetchRow()” method belonging to the “Result” class, for fetching the records and display the results on the browser. Undoubtedly, taking a look at each line of code, we can clearly see what’s happening in every instance.

Besides, we use “countRows()” to display the total number of articles returned by the query. Very simple, eh?

Okay, let’s go one step forward and add a record to the database table, like this:

// include class files

require_once 'mysqlclass.php';

require_once 'resultclass.php';

// instantiate a MySQLConnector object

$options=array('host'=>'localhost','user'=>'user','password'=>'password',
'database'=>'articles');

$db=&new MySQLConnector($options);

// build query

$sql="INSERT INTO articles SET name='Building a Template Parser class with PHP - Part 3',site='Devshed.com'";

// insert new row

$result=$db->performQuery($sql);

// display information about last record inserted

echo 'Data from the last record inserted:<br />';

$sql="SELECT * FROM articles WHERE articleid='".$result->getInsertID()."'";

$result=$db->performQuery($sql);

$row=$result->fetchRow();

echo $row['articleid'].$row['name'].$row['site'];

In this example, we insert a new article into the “articles” database table, and next we display some information about the last entry, using the “getInsertID()” method, as listed below:

$sql="SELECT * FROM articles WHERE articleid='".$result->getInsertID()."'";

Finally, we perform the query, showing the data associated with the article:

echo $row['articleid'].$row['name'].$row['site'];

Now, let’s update an specific record within the “articles” table, using again the provided methods:

// include class files

require_once 'mysqlclass.php';

require_once 'resultclass.php';

// instantiate a MySQLConnector object

$options=array('host'=>'localhost','user'=>'user','password'=>'password',
'database'=>'articles');

$db=&new MySQLConnector($options);

// build query

$sql="SELECT * FROM articles WHERE name='Building a Template Parser class with PHP - Part 1'";

// perform query

$result=$db->performQuery($sql);

$row=$result->fetchRow();

// build query

$sql="UPDATE articles SET name='Building a Template Parser class with PHP - Part 3',site='Devshed.com' WHERE articleid='".$row['articleid']."'";

// perform query

$db->performQuery($sql);

In this case, we update a particular database record in a two-step sequence. The first step performs a SELECT statement to return the row that we want to be updated. Once we’ve gathered the row’s ID , we use it to perform the UPDATE query, in this way updating the specific record. Of course, the same operation might be carried out with a single SQL UPDATE statement, but here we’re demonstrating the clear use of both classes.

Lastly, let’s complete the trip, by deleting a database record. The process is as simple as this:

// include class files

require_once 'mysqlclass.php';

require_once 'resultclass.php';

// instantiate a MySQLConnector object

$options=array('host'=>'localhost','user'=>'user','password'=>'password',
'database'=>'articles');

$db=&new MySQLConnector($options);

// build query

$sql="DELETE FROM articles WHERE name='Building a Template Parser class with PHP - Part 3'";

// perform query

$db->performQuery($sql);

In a similar way, we delete a specific row from the database table. However, as applicable to UPDATE statements, don’t ever forget to add a WHERE clause to the query. Otherwise you’ll delete all of the rows from your carefully crafted table!

Well, I think that our examples are more than enough to demonstrate the flexibility and power that composition offers to developers. Just compare the above code with a procedural approximation, and surely you’ll see the benefits of packaging all of the internal processing to make the connections, execute queries, format results, handle errors, in a set of classes that do the hard work “behind the scenes.” Definitely, this approach is something that must be strongly considered.

Conclusion

In this series, we’ve gone over the basics of composition in PHP, in order to illustrate with copious examples its capability in several situations. While this is not meant to say that every possible project should be conceived for being set up using classes, as websites evolve to more complex applications, the object-oriented schema has proven to be a lot more efficient. So, you have the background, the tools and that pinch of willpower to implement a wealth of OOP resources in your projects. Trust me, you won’t be disappointed. 



 
 
>>> 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: