PHP
  Home arrow PHP arrow Page 4 - Object Interaction in PHP: Introduction to Composition, conclusion
Dev Shed Forums  
Administration  
AJAX  
Apache  
BrainDump  
DHTML  
Flash  
Java  
JavaScript  
Multimedia  
MySQL  
Oracle  
Perl  
PHP  
Practices  
Python  
Reviews  
Security  
Smartphone Development  
Style-Sheets  
Web Services  
XML  
Zend  
Zope  
Mobile Linux  
App Generation ROI  
IBM® developerWorks  
Forums Sitemap  
E-Commerce Hosting  
Linux Web Hosting  
Managed Hosting  
Small Business Hosting  
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? 
Google.com  
PHP

Object Interaction in PHP: Introduction to Composition, conclusion
By: Alejandro Gervasio
  • Search For More Articles!
  • Disclaimer
  • Author Terms
  • Rating: starstarstarstarstar / 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:
      error-file:tidyout.log Del.ici.ous error-file:tidyout.log Digg
      error-file:tidyout.log Blink error-file:tidyout.log Simpy
      error-file:tidyout.log Google error-file:tidyout.log Spurl
      error-file:tidyout.log Y! MyWeb error-file:tidyout.log 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. 



     
     
    >>> More PHP Articles          >>> More By Alejandro Gervasio
     

       

    PHP ARTICLES

    - Implementing Factory Methods in PHP 5
    - Merging a File Split for FTP Upload using PHP
    - Getting Data from Yahoo Site Explorer Inboun...
    - Method Chaining: Adding More Selecting Metho...
    - How to Split a File During an FTP Upload Usi...
    - Expanding a Custom CodeIgniter Library with ...
    - Using the Yahoo Site Explorer Inbound Links ...
    - Building a CodeIgniter Custom Library with M...
    - Building an E-mini Trading System Using PHP ...
    - Completing the MySQL Class with Method Chain...
    - Building Dynamic Queries with Chainable Meth...
    - PHP Encryption and Decryption Methods
    - Building a MySQL Abstraction Class with Meth...
    - Completing a Sample String Processor with Me...
    - Mastering WHILE Loops for PHP and MySQL





    © 2003-2009 by Developer Shed. All rights reserved. DS Cluster 2 Hosted by Hostway
    For more Enterprise Application Development news, visit eWeek