An Introduction to Building Proxy Classes with PHP 5

If you create object-oriented programs in in PHP 5, you know that their performance can be improved by rationalizing the use of objects. The proxy pattern can help with this task. In this first of a two-part series, you will learn the key points of how to use this pattern with PHP 5.

Introduction

During your life as PHP developer, quite possibly you’ll have learned some useful approaches to improve the overall performance of object-based web applications. From using content/XHTML caching mechanisms and compressing web page outputs, to implementing a rational usage of the objects utilized by a given application, options are numerous. Logically, the best of this variety of possible improvements rests on the point that many of the methods I mentioned can be used in conjunction with applications that have been written using a procedural methodology.

Nevertheless, when it comes to working solely with object-oriented programs in PHP, it’s possible to create applications that present a carefully-planned utilization of their different objects. One of the simplest approaches, implemented to avoid the duplication of costly objects, involves using the popular references in PHP 4 instead of working with multiples copies of the objects in question.

However, if you’re looking for new techniques aimed at improving the performance of object-based PHP applications as a whole, I must say that there’s more good news on the horizon: in the huge terrain of creational design patterns, there’s one that can be used successfully for implementing a rational usage of objects. In this case, I’m referring specially to the proxy pattern, which offers many interesting features that can help to reduce significantly the overhead of an application.

But I’m sure you’re wondering how this pattern works. Well, in short, in the proxy pattern, one object is created by another only when the functionality of the first one is required. This avoids unnecessary class instantiation. For this pattern in particular, the object called “proxy” is responsible for handling all the accesses to another class, something that looks very similar to the behavior of different proxy servers. Now, are you feeling more familiar with the functionality of this useful pattern? I’m sure you are.

Having introduced the basic definition of proxy objects in PHP, in this two-part series, I’m going to walk you through the key points of how to use this pattern with PHP 5, as well as how to apply it in different real-world situations.

With the preliminaries out of our way, let’s start learning more about this handy design pattern. Let’s go!

{mospagebreak title=Developing an expandable XML processor class}

Proxy objects can be easily created by defining a simple class that works as an intermediate entity for another one (this resembles the concept of proxy servers). In this case, the proxy is responsible for accessing a class in particular, which will be instantiated only when its functionality is required.

Actually, the above definition seems rather hard to grasp, so let me show you an illustrative example where a proxy class is created to access a generic XML processor only when this object is needed by a specific application.

Having said that, here is the initial signature that corresponds to the mentioned proxy class, which not surprisingly I called “ProxyXMLProcessor.” Have a look at the definition for this new class, please:

// define 'ProxyXMLProcessor' class (proxy class for XMLProcessor) class ProxyXMLProcessor{ private $XMLProcessor=NULL; private $xmlstr; // XMLProcessor is not created here by the constructor public function __construct($xmlstr){ $this->xmlstr=$xmlstr; } // display nodes public function displayNodes($node){ // XMLProcessor object is only instantiated when any
of its methods is called if($this->XMLProcessor==NULL){ $this->createXMLProcessor(); } return $this->XMLProcessor->displayNodes
($node); } // fetch nodes as array of objects public function fetchNodesAsObjects(){ if($this->XMLProcessor==NULL){ $this->createXMLProcessor(); } return $this->XMLProcessor->fetchNodesAsObjects(); } }

If you take some time and examine the class shown above, then you’ll realize that undoubtedly there are some interesting aspects concerning its definition. First, the referenced proxy class really behaves as an intermediate entity for an XML processor object, since all the methods that belong to it are accessed via the proxy. This concept is simple, right?

In addition, you can see that the previous “ProxyXMLProcessor” class also offers a couple of straightforward methods for fetching and displaying the nodes of an inputted XML string. However, one thing that surely caught your attention is the fact that these methods will instantiate the corresponding XML processor object via the respective “createXMLProcessor()” method only when its functionality is required. Period.

Now, do you see why this pattern is aimed at avoiding the unnecessary instantiation of different objects? I hope you do!

Now that you hopefully grasped the logic that stands behind the proxy pattern, let me go one step further and show you how to improve the “ProxyXMLProcessor” class by expanding its existing functionality, in addition to implementing its still undefined “createXMLProcessor” method.

As you might have guessed, all these tasks will be discussed in the following section, thus click on the link below and keep reading.

{mospagebreak title=Expanding the functionality of the ProxyXMLProcessor class}

As I stated in the section that you just read, my main purpose here is to extend the functionality of the already familiar proxy class, in addition to implementing its “createXMLProcessor()” method. Of course, the method will be responsible for the instantiation of XML processor objects only when its presence will be required, in this way sticking to the definition of the proxy pattern.

Having said that, below I listed an improved version of the prior proxy class, this time including some additional methods for counting the number of nodes of an input XML string. This new incarnation of this class looks like this:

// define 'ProxyXMLProcessor' class (proxy class for XMLProcessor) class ProxyXMLProcessor{ private $XMLProcessor=NULL; private $xmlstr; // XMLProcessor is not created here by the constructor public function __construct($xmlstr){ $this->xmlstr=$xmlstr; } // display nodes public function displayNodes($node){ // XMLProcessor object is only instantiated when any
of its methods is called if($this->XMLProcessor==NULL){                  $this->createXMLProcessor();                 }                 return $this->XMLProcessor->displayNodes($node); } // fetch nodes as array of objects public function fetchNodesAsObjects(){ if($this->XMLProcessor==NULL){                  $this->createXMLProcessor();                 } return $this->XMLProcessor->fetchNodesAsObjects();         } // count number of nodes contained into XML string public function countNodes(){ if($this->XMLProcessor==NULL){ $this->createXMLProcessor(); }                 return $this->XMLProcessor->countNodes();       } // instantiate XMLProcessor object private function createXMLProcessor(){ $xmlObj=new XMLProcessor($this->xmlstr); $this->XMLProcessor=$xmlObj->getXMLProcessor(); } }

Aside from implementing a new method for counting the nodes of a given XML string, the above class also exposes a private method called “createXMLProcessor.” In this case, the method in question is tasked with instantiating an XML processor object when this condition is demanded. That was pretty simple, wasn’t it?

Okay, at this stage, I’m pretty certain that you understand how the previous proxy class does its business. However, I have to admit that there’s still a missing piece in this puzzle that remains undefined, since you don’t know how the corresponding “XMLProcessor” class looks.

In order to address this issue and dissipate any possible doubts, in the next few lines I’m going to show you the respective signature for this XML processing class. Go ahead and read the next section.

{mospagebreak title=Defining the XMLProcessor class}

In consonance with the concepts related to the proxy pattern that you learned before, it’s necessary to define the signature of the corresponding “XMLProcessor” class. This will help you understand how a potential proxy object can access the methods that belong to different XML processors.

This being said, below I included the signature for the pertinent “XMLProcessor” class. You’ll quickly realize that it performs some useful tasks on a given XML string. Therefore, have a look at this brand new class, please:

// define 'XMLProcessor' class class XMLProcessor{ private $sxmle; public function __construct($xmlstr){ if(!$this->sxmle=new SimpleXMLElement($xmlstr)){ throw new Exception('Error reading XLML
string'); } } // display values of a given node public function displayNodes($node){ $nodes=''; foreach($this->sxmle as $obj){ $nodes.='Value of '.$node.' node is the
following : '.$obj->$node.'<br />'; } return $nodes;   } // fetch all nodes as array of objects public function fetchNodesAsObjects(){ $nodes=array(); foreach($this->sxmle as $node){ $nodes[]=$node; } return $nodes; } // count number of nodes contained into XML string public function countNodes(){ $nodeCounter=0; foreach($this->sxmle as $node){ $nodeCounter++; } return $nodeCounter; } // get 'SimpleXMLElement' object public function getXMLProcessor(){ return $this; } }

As shown above, the “XMLProcessor” class has been provided with a wealth of handy methods which can be used for counting and displaying the different nodes of a specified XML string, in addition to fetching the complete set of XML data as an array of objects. Though all the methods that I just described play an important role in the context of the XML processing class in question, I’d like you to focus your attention on the definition of the “getXMLProccessor()” method.

As you can see, the only task assigned to the referenced method consists of simply returning to calling code an instance of the corresponding XMLProcessor” class. Logically, this condition allows a proxy class to access all the methods that belong to the respective XML processor, something that perfectly suits the requirements established by the proxy pattern.

All right, at this level I hope that you grasped the key points on how the previous XML processing class does its thing, since its signature is indeed pretty straightforward. Thus, bearing this condition in mind, the only thing that remains undone is developing an illustrative example that will show you how the XML proxy class and its respective target object can work in tandem to process a simple XML string.

Naturally, the example will be shown in the following section, thus to see how it will be created, please click on the link that appears below and keep reading.

{mospagebreak title=Seeing the proxy class in action}

In accordance with the concepts that I deployed in the prior section, the simplest way to understand how the corresponding “ProxyXMLProcessor” class works to access all the methods of a potential XML processor object rests on setting up a comprehensive example. In this example, a simple XML string will be processed by using the proxy pattern.

For this specific case, say you have the following sample XML string in a file called “xmlstr.php:”

<?php $xmlstr=<<<XML <?xml version="1.0" encoding="iso-8859-1"?> <users> <user> <name>John Doe</name> <location>Location 1</location> <email>john@domain.com</email> </user> <user> <name>Mary Shelley</name> <location>Location 2</location> <email>mary@domain.com</email> </user> <user> <name>Peter Parker</name> <location>Location 3</location> <email>peter@domain.com</email> </user> <user> <name>Susan Norton</name> <location>Location 4</location> <email>susan@domain.com</email> </user> <user> <name>Steve Powell</name> <location>Location 5</location> <email>steve@domain.com</email> </user> </users> XML; ?>

Now, after listing the above XML string, it’s possible to use the previous XML proxy class in the following way:

try{ // include XML string require_once 'xmlstr.php'; // instantiate 'ProxyXMLProcessor' object $pxmlproc=new ProxyXMLProcessor($xmlstr); // display number of 'email' nodes contained into XML string echo $pxmlproc->displayNodes('email'); /* displays the following:            Value of email node is the following : john@domain.com Value of email node is the following : mary@domain.com Value of email node is the following : peter@domain.com Value of email node is the following : susan@domain.com Value of email node is the following : steve@domain.com */          // fetch nodes as array of objects echo $pxmlproc->fetchNodesAsObjects(); /* displays the following: array */ // count number of nodes contained into XML string             echo $pxmlproc->countNodes(); /*           displays the following: 5 */ } catch(Exception $e){ echo $e->getMessage(); exit(); }

As you can see, the previous example shows clearly how the corresponding “XMLProxyProcessor” can be used to count, display and fetch all the nodes contained in the XML string that you saw before, by using all the methods exposed by an XML processor object.

After studying the above example, you’ll agree with me that building proxy classes with PHP 5 is indeed a no-brainer process, right?

Wrapping up

We’ve come to the end of this first part of the series. Aside from introducing the core concepts for how to implement the proxy pattern with PHP 5, I provided you with some examples that may help you understand more easily how this pattern works.

In the final article of this series, I’ll show you how to use this handy pattern to construct a proxy object for the “DirectoryIterator” class that comes bundled with PHP 5. So, stay tuned until the next part!  

[gp-comments width="770" linklove="off" ]

antalya escort bayan antalya escort bayan Antalya escort diyarbakir escort