PHP
  Home arrow PHP arrow Page 2 - 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 - Composition in a practical sense: building a MySQL wrapping class


    (Page 2 of 4 )

    A MySQL wrapping class is one of the most common applications that we use very often, and certainly there are lots of good places on the Web where we can look for database classes. One of my favorites is PEAR::DB, which provides a lot of room to work with different database systems, and offers a wealth of advanced features, powerful enough to keep you entertained for a long time. If you feel curious about it, please visit http://pear.php.net/package/DB and give it a try.

    However, for the purposes of this article, we’ll work with our own MySQL abstraction class, so we can see how composition is properly carried out. Building such a class is a pretty straightforward process, which has been covered in some of my previous articles explaining aggregation in PHP. Thus, I guess the creation process shouldn’t pose any difficulties.

    Now, armed with a decent background about PHP database classes, we might define our own version in the following way:

    class MySQLConnector {

                var $conId; // connection identifier

                var $host; // MySQL host

                var $user; // MySQL username

                var $password; // MySQL password

                var $database; // MySQL database

                // constructor

                function MySQLConnector($options=array()){

                            // validate incoming parameters

                            if(count($options)>0){

                                       foreach($options as $parameter=>$value){

                                                   (!empty($value))?$this->{$parameter}=$value:die('Invalid parameter '.$parameter);

                                       }

                                       // connect to MySQL

                                       $this->connectDB();

                            }

                            else {

                                       die('No connection parameters were provided');

                            }

                }

                // connect to MySQL server and select database

                function connectDB(){

                            if(!$this->conId=mysql_connect($this->host,$this->user,$this->password)){

                                        $this->isError('Error connecting to the server');

                            }

                            if(!mysql_select_db($this->database,$this->conId)){

                                        $this->isError('Error selecting database');

                            }

                }

                // perform query

                function performQuery($query){

                            if(!$this->result=mysql_query($query,$this->conId)){

                                       $this->isError('Error performing query '.$query);

                            }

                            // return new Result object

                            return new Result($this,$this->result);

                }

                // display errors

                function isError($errorMsg){

                            die($errorMsg.' '.mysql_error());

                }

    }

    As you can see, the “MySQLConnector” class is closely similar to that presented in previous articles. As usual, the constructor accepts the parameters required to connect to MySQL, that is, host, username, password and the selected database, in the form of an $options array. Then, each parameter is properly validated and finally the connection to the database server is performed by calling the private method “connectDB()”.

    Besides the constructor, the class presents an “isError()” method to handle basically any error that occurred during the course of the MySQL operations, stopping the class with a die statement, and displaying a custom error message along with the error generated by the mysql_error() function.

    However, there is a noticeable difference in the “performQuery()” method. Notice that it takes a SQL query, then performs it against the database table, but this time it returns a new instance of a “Result” object. Here’s the list of the relevant method:

    function performQuery($query){

                if(!$this->result=mysql_query($query,$this->conId)){

                            $this->isError('Error performing query '.$query);

                }

                // return new Result object

                return new Result($this,$this->result);

    }

    Since this method is creating a new “Result” object, we have a clue about what’s happening here. We’ve established a relationship between objects, where the object “Result” composes the “MySQLConnector” object. Indeed, the process of composition becomes very understandable.

    Also, maintaining our database wrapping class as a completely separate piece of code from the “Result” class, implies a immediate benefit, because we’re clearly delimiting the operations related to each class. It’s important to know that we’re not conceiving a class as a bunch of properties and methods that don’t keep a well-defined relationship to each other.

    So far, so good. We have our “MySQLConnector” class, which nicely creates the “Result” object. But, what’s next? It’s time to look at the structure of the “Result” class, so we can see how it works. Just join me in the next explanation.

    More PHP Articles
    More By Alejandro Gervasio


       · 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 3 hosted by Hostway
    Stay green...Green IT