PHP
  Home arrow PHP arrow Page 4 - Object Interaction in PHP: Introductio...
Administration  
AJAX  
Apache  
BrainDump  
DHTML  
Flash  
Java  
JavaScript  
Multimedia  
MySQL  
Oracle  
Perl  
PHP  
Practices  
Python  
Reviews  
Security  
Style-Sheets  
Web Services  
XML  
Zend  
Zope  
Forums Sitemap 
IBM® developerWorks 
Sun Developer Network 
E-Commerce Hosting 
Linux Web Hosting 
Managed Hosting 
Small Business Hosting 
Mobile Linux 
App Generation ROI 
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? 
PHP

Object Interaction in PHP: Introduction to Composition, conclusion
By: Alejandro Gervasio
  • Search For More Articles!
  • Disclaimer
  • Author Terms
  • Rating: 4 stars4 stars4 stars4 stars4 stars / 16
    2005-07-18

    Table of Contents:
  • Object Interaction in PHP: Introduction to Composition, conclusion
  • Composition in a practical sense: building a MySQL wrapping class
  • The other side of composition: the “Result” class
  • Assembling the whole picture: putting the classes to work

  • Rate this Article: Poor Best 
      ADD THIS ARTICLE TO:
      Del.ici.ous Digg
      Blink Simpy
      Google Spurl
      Y! MyWeb 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 Composition, conclusion - Assembling the whole picture: putting the classes to work


    (Page 4 of 4 )

    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. 


    DISCLAIMER: The content provided in this article is not warranted or guaranteed by Developer Shed, Inc. The content provided is intended for entertainment and/or educational purposes in order to introduce to the reader key ideas, concepts, and/or product reviews. As such it is incumbent upon the reader to employ real-world tactics for security and implementation of best practices. We are not liable for any negative consequences that may result from implementing any information covered in our articles or tutorials. If this is a hardware review, it is not recommended to open and/or modify your hardware.

       · This second part of the series makes room to implement Composition by writing...
       · Again, great article. Really learn a lot as I'm working through all your articles on...
       · Hello again Matthijs,Very grateful for the compliments. Also, I'm pleased to...
     

       

    PHP ARTICLES

    - Working With Different Namespaces in PHP 5
    - User Management Explained: Overview
    - Using Namespaces in PHP 5
    - Database Security: Guarding Against SQL Inje...
    - Building a Modular Exception Class in PHP 5
    - Database and Password Security for Web Appli...
    - Handling MySQL Data Set Failures in PHP 5
    - Building Site Registration for Web Applicati...
    - Intercepting Customized Exceptions in PHP 5
    - Securing Your Web Application Against Attacks
    - Sub Classing Exceptions in PHP 5
    - Authentication for Web Application Security
    - Building a Content Management System with Co...
    - Filters and Login Systems for Web Applicatio...
    - Working with the Email Class in Code Igniter





    © 2003-2008 by Developer Shed. All rights reserved. DS Cluster 6 hosted by Hostway
    Stay green...Green IT