PHP
  Home arrow PHP arrow Page 4 - Working with MySQL Result Sets and the Decorator Pattern in PHP
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

Working with MySQL Result Sets and the Decorator Pattern in PHP
By: Alejandro Gervasio
  • Search For More Articles!
  • Disclaimer
  • Author Terms
  • Rating: starstarstarstarstar / 12
    2006-09-05


    Table of Contents:
  • Working with MySQL Result Sets and the Decorator Pattern in PHP
  • Handling MySQL result sets
  • Retrieving MySQL result sets without changing the original class
  • Defining multiple decorator classes

  • 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


    Working with MySQL Result Sets and the Decorator Pattern in PHP - Defining multiple decorator classes
    ( Page 4 of 4 )

    As I said previously, having a result set decorator class which behaves like a bridge between the original class and further ones makes constructing new decorator classes a simple process.

    To demonstrate the veracity of my concepts, I’ll begin creating some simple decorator classes, where each of them is tasked with taking a MySQL result set and returning it in a different format. The list of these new classes starts with the “StringResultDecorator” class, which has been defined as follows:

    class StringResultDecorator extends ResultDecorator{
        private $resultDecorator;
        // pass 'ResultDecorator' object to the constructor
        public function __construct(ResultDecorator $resultDecorator){
            $this->resultDecorator=$resultDecorator;
        }
        // display result set as formatted string
        public function displayString(){
            $result=$this->resultDecorator->resultSet;
            $str='';
            while($row=mysql_fetch_assoc($result)){
                $str.=$row['id'].' '.$row['name'].' '.$row
    ['email'].'<br />';
            }
            return $str;
        }
    }

    Did you think that building another decorator class was really harder? Not at all! As you can see, the above class accepts an object of type “ResultDecorator” and returns a completely formatted result set, via its “displayString()” method. In this case, I used only a “<br />” tag for modeling the respective dataset, but this might be entirely modified to include more complex tag formatting.

    As shown above, implementing the decorator pattern allowed me to add more functionality to the original “Result” class, without having to change its initial structure. Indeed, this is a very cool and handy concept.

    Now, let me show you how to create a couple of additional decorator classes, which are capable of returning MySQL result sets, both as XML data and arrays respectively. The definitions of these classes are listed below, therefore please examine their source code:

    // define 'ArrayResultDecorator' class
    class XMLResultDecorator extends ResultDecorator{
        private $resultDecorator;
        // pass 'ResultDecorator' object to the constructor
        public function __construct(ResultDecorator $resultDecorator){
            $this->resultDecorator=$resultDecorator;
        }
        // display result set as formatted string
        public function displayXML(){
            $result=$this->resultDecorator->resultSet;
            $xml='<?xml version="1.0" encoding="iso-8859-1"?>';
            $xml.='<users>'."n";
            while($row=mysql_fetch_assoc($result)){
                $xml.='<user><id>'.$row['id'].'</id><name>'.$row
    ['name'].'</name><email>'.$row['email'].'</email></user>'."n";
            }
            $xml.='</users>';
            return $xml;
        }
    }
    // define 'ArrayResultDecorator' class
    class ArrayResultDecorator extends ResultDecorator{
        private $resultDecorator;
        private $resultArray=array();
        // pass 'ResultDecorator' object to the constructor
        public function __construct(ResultDecorator $resultDecorator){
            $this->resultDecorator=$resultDecorator;
        }
        // get result set as array
        public function getArray(){
            $result=$this->resultDecorator->resultSet;
            while($row=mysql_fetch_row($result)){
                $this->resultArray[]=$row;
            }
            return $this->resultArray;
        }
    }

    As you’ll surely realize with reference to the above classes, they’re very similar to the previous one. In this case, both of them also take an object of type “ResultDecorator” and return differently-formatted result sets by their “displayXML()” and “getArray()” method respectively.

    What makes these classes really interesting is their capability to expand the functionality of the original “Result” class without having to modify its signature. This is what I would call a good example of the decorator pattern in action!

    Well, now that you know how all the decorator classes look, it’s time to put them to work, so you can have a better idea of how they fit into the potential context of a Web application. For this reason, below I’ve set up an example which shows how to use each class separately. Please have a look:

    try{
        // connect to MySQL
        $db=new MySQL(array
    ('host'=>'host','user'=>'user','password'=>'password',
    'database'=>'mydatabase'));
        // get result set
        $result=$db->query('SELECT * FROM users');
        // instantiate 'ResultDecorator' object
        $resultDecorator=new ResultDecorator($result);
        // instantiate 'StringResultDecorator' object
        $strResultDecorator=new StringResultDecorator
    ($resultDecorator);
        // display result set as formatted string
        echo $strResultDecorator->displayString();
    }
    catch(Exception $e){
        echo $e->getMessage();
        exit();
    }

    In the above example, first I established a connection to MySQL, then fetched a result set from a hypothetical “USERS” database table, and finally returned it as a formatted string, by using the “displayString()” method. Short and simple, right?

    Now, suppose you want to return the same MySQL result set, but this time as XML data. The below script does precisely that:

    try{
        // connect to MySQL
        $db=new MySQL(array
    ('host'=>'host','user'=>'user','password'=>'password',
    'database'=>'mydatabase'));
        // get result set
        $result=$db->query('SELECT * FROM users');
        // instantiate 'ResultDecorator' object
        $resultDecorator=new ResultDecorator($result);
        $xmlResultDecorator=new XMLResultDecorator($resultDecorator);
        header('Content-Type: text/xml');
        // display result set as XML data
        echo $xmlResultDecorator->displayXML();
    }
    catch(Exception $e){
        echo $e->getMessage();
        exit();
    }

    And lastly, the example ends by showing how to return the result set in question as an array structure:

    try{
        // connect to MySQL
        $db=new MySQL(array
    ('host'=>'host','user'=>'user','password'=>'password',
    'database'=>'mydatabase'));
        // get result set
        $result=$db->query('SELECT * FROM users');
        // instantiate 'ResultDecorator' object
        $resultDecorator=new ResultDecorator($result);
        $arrayResultDecorator=new ArrayResultDecorator
    ($resultDecorator);
        // get result set as array
        echo $arrayResultDecorator->getArray();
    }
    catch(Exception $e){
        echo $e->getMessage();
        exit();
    }

    All right, as you saw, returning MySQL result sets in different formats without changing the initial definition of the pertinent “Result” class is a no-brainer process, considering the correct implementation of the decorator pattern in PHP. Of course, I should mention that the same result might be obtained with inheritance, but as I stated before, there are times when you need to work with objects of different types.

    Final thoughts

    Sad but true, our journey surrounding the creation of decorator classes has ended. I hope that all the practical examples that you learned here will serve as a good introduction for understanding the development and application of decorator objects in PHP even better. See you in the next PHP tutorial!



     
     
    >>> 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 1 Hosted by Hostway
    For more Enterprise Application Development news, visit eWeek