PHP
  Home arrow PHP arrow Page 2 - 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? 
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 - 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
     

       

    PHP ARTICLES

    - 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
    - Method Chaining: Adding More Methods to the ...
    - Method Chaining in PHP 5
    - The Role of Interfaces in Applying the Depen...
    - Dependency Injection: Using a Setter Method ...
    - Using a Model Class with the Dependency Inje...
    - Injecting Objects Using Setter Methods with ...
    - Injecting Objects by Constructor with the De...
    - The Dependency Injection Design Pattern in P...
    - Performing Inferential Statistical Analysis ...
    - Performing Descriptive Statistical Analysis ...





    © 2003-2009 by Developer Shed. All rights reserved. DS Cluster 3 Hosted by Hostway
    Stay green...Green IT