Home arrow PHP arrow Page 4 - Working with MySQL Result Sets and the Decorator Pattern in PHP

Defining multiple decorator classes - PHP

If you’re one of those avid PHP developers who wants to learn how to apply the decorator design pattern within your Web applications, then this group of articles might be quite appealing to you. Welcome to the second part of the series “Using the Decorator pattern with PHP.” Comprised of two parts, this series walks you through the core concepts of using this pattern in PHP, and shows you its practical edge with numerous hands-on examples.

TABLE OF CONTENTS:
  1. Working with MySQL Result Sets and the Decorator Pattern in PHP
  2. Handling MySQL result sets
  3. Retrieving MySQL result sets without changing the original class
  4. Defining multiple decorator classes
By: Alejandro Gervasio
Rating: starstarstarstarstar / 12
September 05, 2006

print this article
SEARCH DEV SHED

TOOLS YOU CAN USE

advertisement

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
 

blog comments powered by Disqus
   

PHP ARTICLES

- Hackers Compromise PHP Sites to Launch Attac...
- Red Hat, Zend Form OpenShift PaaS Alliance
- PHP IDE News
- BCD, Zend Extend PHP Partnership
- PHP FAQ Highlight
- PHP Creator Didn't Set Out to Create a Langu...
- PHP Trends Revealed in Zend Study
- PHP: Best Methods for Running Scheduled Jobs
- PHP Array Functions: array_change_key_case
- PHP array_combine Function
- PHP array_chunk Function
- PHP Closures as View Helpers: Lazy-Loading F...
- Using PHP Closures as View Helpers
- PHP File and Operating System Program Execut...
- PHP: Effects of Wrapping Code in Class Const...

Developer Shed Affiliates

 



© 2003-2013 by Developer Shed. All rights reserved. DS Cluster - Follow our Sitemap

Dev Shed Tutorial Topics: