Introducing Builder Objects in PHP 5

In this article, the first of a three-part series, you will be introduced to the basics of creating directors and builder objects with PHP 5. As usual, there will be copious examples to help you quickly start using the builder pattern in your own PHP projects.

Introduction

In PHP, as with many other trusted programming languages out there, there are many ways to establish diverse relationships between objects during the development of an application. This concept has an immediate implementation in well-known circumstances within the context of object-based programming, particularly in those cases where both aggregation and composition play a relevant role.

More specifically, if you’ve been using classes inside your PHP applications for a while, then you’ll know that there are several programming environments where a particular object isn’t completely independent. It requires the “assistance” of one or many additional objects to perform a given task.

As I expressed earlier, composition and aggregation are clear examples of well-defined object interaction, but they’re definitely not the only ones that exist in the object-based universe. Even without having a thorough theory that backs you up (using only your common sense), certainly you can conceive of numerous ways for two or more objects to perform a mutual (and productive) interaction, with no need to read thick books on object-oriented programming.

Now, and particularly when using PHP 5, I’d like to introduce a concept that’s strongly related to a specific interaction between multiple objects. In this case, I’m talking about directors and builder objects, which when evaluated in conjunction, conform to what is commonly known as the “builder” pattern. But right now you’re probably wondering how the builder pattern works.

Well, to put things in a simple perspective, when the builder pattern is applied, two objects are put into action to create a third one. First, these two objects create a director; as its name suggests, the director controls all aspects of the creation process and determines what pieces and modifications will be introduced into the target object. Finally, a builder is tasked with constructing the third object in question, in accordance with particular specifications. Sounds fairly simple, doesn’t it?

Since you might have to address specific issues by applying the mentioned builder pattern eventually, in this series you’ll learn how to use it, and of course how to get the most out of it.

Are you ready to learn more on how to use directors and builder objects in PHP? Let’s get started!

{mospagebreak title=Building basic XML documents: definition of the target object}

After reading the article’s introduction, quite possibly you’re still wondering whether it is possible to involve two specific objects in creating a third one which is responsible for performing a particular task. Fortunately for you and me, the answer is a resounding yes.

By applying the concept of directors and builders, it’s feasible to build another object in such a way that the entire creation process can be conducted in accordance with the orders (or directives) dictated by a director.

I know that all this may sound fairly complicated, at least when analyzed from the raw theory, but things can be more complex, particularly if you want to translate the definitions of directors and builders to functional PHP code. Precisely for that reason, since I want you to learn how to include these types of objects inside your own PHP applications, I’ll set up an educational example. It will show you how to apply the builder pattern quickly.

To begin, suppose you need to define a PHP class and give it the ability to construct basic XML documents. Given that idea, the structure of the mentioned class might look like this:

// 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"
encoding="iso-8859-1"?>'."n".'<data>'."n";
 		foreach($this->nodes as $node){       
 			$xml.='<node>'.$node.'</node>'."n";
		}
		$xml.='</data>';
		return $xml;
	}
}

 

As you can see, the above defined “XMLPage” class has been provided with the capacity to construct simple XML documents. This is convenient for demonstrating how the builder pattern can work. With reference to the previous class, you’ll probably realize that the method listed below:

 

public function getXMLPage(){
	$xml='<?xml version="1.0"
encoding="iso-8859-1"?>'."n".'<data>'."n";
	foreach($this->nodes as $node){
		$xml.='<node>'.$node.'</node>'."n";
	}
	$xml.='</data>';
	return $xml;
}

 

is the real workhorse for creating a concrete XML page, since it returns to the calling code the corresponding XML output. Also, it should be noticed that the “XMLPage” class has another handy method, called “addXMLNode()” that allows you to add new nodes dynamically to the current XML document.

So far, the previously listed class should be fairly easy to understand since its definition is comprehensive. However, there isn’t yet a clear indication of how two additional PHP objects, that is a director and a builder respectively, can be used together to define programmatically how each XML page should be created. However, fear not since this process is about to be revealed in the following section!

Therefore, if you’re intrigued by learning how directors and builders can be created with PHP, keep reading. Trust me, things are getting really exciting now!

{mospagebreak title=Of builders and XML pages: the programmatic creation process}

As you learned in the course of the previous section, the “XMLPage” class was tasked with creating basic XML documents. Aside from showing you its rather limited functionality, I want you to understand how a director and a builder together can fit into the whole picture.

First off, let me demonstrate the complete process for defining a builder object, to give you a better idea of how it works with reference to the prior example. Essentially, if I want to create a builder class, which will be directly responsible for the correct creation of different XML pages, I might define the following class:

// define abstract 'AbstractXMLBuilder' class

abstract class AbstractXMLBuilder{

	abstract function getXMLPage();

}

As you can see, what I did above was simply define the general structure of an XML builder object that has a unique method called “getXMLPage().” Of course, the point of creating the above abstract class is merely to establish the generic signature of all the eventual objects that belong to the “AbstractXMLBuilder” class.

Still with me? Fine, now let me go one step further and specify a concrete implementation for the abstract builder class that you saw before. Based upon its structure, its concrete version would look like this:

// define concrete 'XMLBuilder' class

class XMLBuilder extends AbstractXMLBuilder{

	private $xmlPage;

	public function__construct(){
   
		$this->xmlPage=new XMLPage();

	}

	// add new XML node

	public function addXMLNode($nodeValue){
      
		$this->xmlPage->addXMLNode($nodeValue);

	}

	// get source code of XML page

	public function getXMLPage(){

	return $this->xmlPage->getXMLPage();

	}

}

Now, things should be much clearer to you, since the above class offers a concrete implementation for the “getXMLPage()” method that was declared previously. In addition, I’d like to stress how the corresponding constructor performs the instantiation of the target object, in this case referenced as “XMLPage,” to use all its methods for constructing the pertinent XML document. That was simple to learn, wasn’t it?

Okay, at this stage you have hopefully grasped all the concepts behind creating a builder class. As you saw, all the mentioned class does is take up an object of type “XMLPage” and use its methods to render a basic XML document. However, when it comes to applying the builder pattern, I said initially that there were two objects involved in the complete creation process. Since you already learned now to create a builder, the missing piece here is obviously the director!

Basically, this second object will indicate programmatically to the builder the manner in which the respective XML pages must be generated, completing the creation procedure that I discussed before, based on two primary objects. Do you see now how the pieces start fitting together?

Now that you understand how a builder class can be defined with PHP, let’s move forward and see how the corresponding director can be created. To learn how this will be achieved, you must click on the link below and keep reading.

{mospagebreak title=Taking control of the process: a director class}

Defining a director class is a procedure closely similar to the one shown when creating the respective builder, therefore I think you should grasp the concept very quickly. As I did before, I’ll begin by defining an abstract class, which will set up the generic structure for all the eventual director objects.

Having said that, here is the signature of the brand new “AbstractXMLDirector” class. Please take a look at it:

// define abstract 'AbstractXMLDirector' class

abstract class AbstractXMLDirector{

	abstract function __construct(AbstractXMLBuilder $xmlBuilder);

	abstract function buildXMLPage();

	abstract function getXMLPage();

}

As you can see, the above abstract class simply establishes the skeleton of all the objects that will be created from it. Notice the declaration of two primary methods aside from the respective constructor, called “buildXMLPage()” and “getXMLPage()” respectively.

In short, these will be responsible for instructing the previous builder about the way that all the XML pages should be created. Now, do you see why this class has been called the “director?” Certainly, it’s a faithful representation with PHP code of your own boss.

Now, leaving the jokes apart, please take a look at the following class’ source code, which shows a concrete implementation for the prior “AbstractXMLDirector” class:

// define concrete 'XMLDirector' class

class XMLDirector extends AbstractXMLDirector{

	// accept 'XMLBuilder'object

	public function __construct(AbstractXMLBuilder $xmlBuilder){
     
		$this->xmlBuilder=$xmlBuilder;

	}

	// build XML page

	public function buildXMLPage(){
      
		$this->xmlBuilder->addXMLNode('This is node 1');
      
		$this->xmlBuilder->addXMLNode('This is node 2');
      
		$this->xmlBuilder->addXMLNode('This is node 3');

		$this->xmlBuilder->addXMLNode('This is node 4');
   
		$this->xmlBuilder->addXMLNode('This is node 5');
      
		$this->xmlBuilder->addXMLNode('This is node 6');

	}

	// return XML page to calling code

	public function getXMLPage(){

		header('Content-Type:text/xml');

		return $this->xmlBuilder->getXMLPage();

	}

}

As shown above, now the brand new “XMLDirector” class exposes the corresponding concrete methods to instruct the builder in question on how all the XML pages must be created. In addition, it should be noted how the builder object itself is fed straight into the constructor, which comes in handy for using all its methods.

Al right, after understanding how the previous director class works, I guess that it’s also easy seeing how the builder pattern can be used for building target objects. In this case, the appropriate combination of the director and builder objects respectively results in the adequate creation of XML pages.

However, before you finish reading this tutorial, I’d like to show you how all the classes that I defined previously can be used together to generate programmatically some XML pages. Therefore, in the next few lines, you’ll see the builder pattern in action. Thus I suggest you to jump straight into the following section. I’ll be there, waiting for you.

{mospagebreak title=Putting all the classes to work together}

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"
encoding="iso-8859-1"?>'."n".'<data>'."n";       foreach($this->nodes as $node){       $xml.='<node>'.$node.'</node>'."n"; } $xml.='</data>'; return $xml; }

 

} // define concrete 'XMLBuilder' class class XMLBuilder extends AbstractXMLBuilder{ private $xmlPage; public function __construct(){        $this->xmlPage=new XMLPage(); } // add new XML node public function addXMLNode($nodeValue){        $this->xmlPage->addXMLNode($nodeValue); } // get source code of XML page public function getXMLPage(){ return $this->xmlPage->getXMLPage(); } } // define concrete 'XMLDirector' class class XMLDirector extends AbstractXMLDirector{ // accept 'XMLBuilder'object public function __construct(AbstractXMLBuilder $xmlBuilder){       $this->xmlBuilder=$xmlBuilder;

 

} // build XML page public function buildXMLPage(){ $this->xmlBuilder->addXMLNode('This is node 1');       $this->xmlBuilder->addXMLNode('This is node 2');       $this->xmlBuilder->addXMLNode('This is node 3');         $this->xmlBuilder->addXMLNode('This is node 4');       $this->xmlBuilder->addXMLNode('This is node 5');     $this->xmlBuilder->addXMLNode('This is node 6'); } // return XML page to calling code public function getXMLPage(){         header('Content-Type: text/xml'); return $this->xmlBuilder->getXMLPage(); } }

 

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!

[gp-comments width="770" linklove="off" ]
antalya escort bayan antalya escort bayan