As I stated before, below I’ve coded a short script which demonstrates how to use the pertinent director and builder classes to generate a basic XML document. Please look at the following example:
try{
// instantiate 'XMLBuilder' object
$xmlBuilder=new XMLBuilder();
// instantiate 'XMLDirector' object
$xmlDirector=new XMLDirector($xmlBuilder);
// build XML page
$xmlDirector->buildXMLPage();
// display XML page
echo $xmlDirector->getXMLPage();
}
catch(Exception $e){
echo $e->getMessage();
exit();
}
Although the above script may seen rather primitive at first glance, indeed it reveals the real power that stands behind the builder pattern. First, a new “XMLBuilder” object is instantiated, which is passed directly to the constructor of the respective “XMLDirector” class. Finally, this uses its own methods to indicate to the builder how an XML page must be created, rendering the following XML document: <?xml version="1.0" encoding="iso-8859-1"?> <data> <node>This is node 1</node> <node>This is node 2</node> <node>This is node 3</node> <node>This is node 4</node> <node>This is node 5</node> <node>This is node 6</node> </data>
Additionally, since I want you to have all the classes that I created previously available in one place, below I listed their corresponding definitions:
// define abstract 'AbstractXMLBuilder' class
abstract class AbstractXMLBuilder{
abstract function getXMLPage();
}
// define abstract 'AbstractXMLDirector' class
abstract class AbstractXMLDirector{
abstract function __construct(AbstractXMLBuilder $xmlBuilder);
abstract function buildXMLPage();
abstract function getXMLPage();
}
// define 'XMLPage' class
class XMLPage{
private $nodes=array();
public function addXMLNode($nodeValue='defaultValue'){
$this->nodes[]=$nodeValue;
}
// create source code for XML page
public function getXMLPage(){
$xml='<?xml version="1.0"
Definitely, after studying the above classes, you’ll agree with me that defining directors and builders with PHP is a no-brainer process! Wrapping up In this first article of the series, I walked you through the basics of creating directors and builder objects with PHP 5. I hope that all the examples you learned here will start you quickly on using the builder pattern in your own PHP projects. In the next article, I’ll demonstrate how to use directors and builders in a more useful fashion: generating online forms. Want to see how this will be done? Read the next part!
blog comments powered by Disqus |