HomePHP Page 3 - An Introduction to Building Proxy Classes with PHP 5
Expanding the functionality of the ProxyXMLProcessor class - PHP
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.
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.