Factoring Content Boxes with the Factory Pattern in PHP 5

Working with factory classes is a rather common process for many PHP developers who build object-based applications on a frequent basis. If you want to find out how to make this helpful class work for you, then this group of articles might be what you need. Welcome to the final installment of the series that began with "Using the Factory Pattern in PHP 5." In three parts, this series goes through the key concepts of implementing the factory pattern with PHP, and complements theory with numerous and educational code samples.

Introduction

Now that I have introduced the subject of this series, let me remind you of some of the most important topics covered in the previous tutorial. As you learned earlier, implementing the factory pattern using an extremely friendly scripting language like PHP is actually a no-brainer process that can be performed with minor hassles.

Creating a simple yet effective factory class, which can be easily provided with the capacity for spawning multiple objects across a given application, is a procedure reduced to something as basic as defining a method for the class in question that has the ability to return to client code a certain type of object, according to the specifications of a determined context.

Besides, as I clearly demonstrated by the copious hands-on examples included in the two previous tutorials of the series, working with only one instance of the factory class is an issue that can be addressed by different approaches. These include applying the Singleton pattern, or even better, calling statically its factory method.

Now that I mentioned it, I used this last approach with all the code samples shown so far; it’s one of the most effective techniques utilized by many PHP programmers. It allows you to create specific objects without having to deal with a concrete instance of a factory class.

However, I’d like to put the tiny details of the factory pattern to the side (at least momentarily) and introduce the topics that I plan to cover in this final article of the series. In this last tutorial I’m going to teach you how to implement this useful pattern to build a bunch of highly-customizable content boxes, which can be quickly included into any web page.

Now that you know what this article is about, let’s move on together and learn how to build these popular and handy elements of today’s web development by using the functionality provided by the factory pattern. Let’s get started!

{mospagebreak title=Factoring web page content boxes}

Although I must admit that the factory pattern can be used with a great variety of real-world applications, such as form and web page generators, database abstraction layers, and so forth, in this case I’m going to demonstrate how to utilize its neat functionality to build different types of content boxes. These boxes can be quickly included into any web document by simply invoking the appropriate factory class.

Basically, the visual appearance that I plan to achieve with these content boxes is illustrated by the picture below:

As you can see, the above image shows pretty clearly how distinct kinds of web page content boxes can be easily created by using the factory pattern, in this way demonstrating yet another useful implementation for this popular pattern.

All right, now that you have seen how the pertinent content boxes are going to look when included into a specific web page, let me show you the respective definition of the factory class that builds them. Here is the signature for the class in question; examine its source code, please:

class ContentBoxFactory{
   public function createContentBox($type,$title,$contents){
     $contentBox=NULL;
     switch($type){
       case "grey";
         $contentBox=new GreyContentBox($title,$contents);
         break;
       case "blue";
         $contentBox=new BlueContentBox($title,$contents);
         break;
       case "yellow";
         $contentBox=new YellowContentBox($title,$contents);
         break;
       default:
         $contentBox=new GreyContentBox($title,$contents);
         break;               
     }
     return $contentBox;
   }
}

See how easy it is to define a basic factory class for building three different types of content boxes? I bet you do! The "ContentBoxFactory" class has been provided with the capacity for returning to client code, a decent variety of content box objects, identified as "GreyContentBox," "BlueContentBox" and "YellowContentBox" respectively.

Obviously, the main difference between the aforementioned content box objects rests upon their background and title colors, something that can be perfectly seen in the image shown a few lines above.

Okay, at this point you hopefully grasped the logic that drives the previous factory class, which indeed presents a simple signature. However, since the prior content boxes need to be included into a sample web document to appreciate their real usefulness, I’m going to build a web page generator class. Its primary function will be creating the CSS styles and web page sections required for using respective content boxes.

Having said that, here is the corresponding definition for this web page generator:

// define ‘WebPage’ class
class WebPage{
   private $title=’Testing the factory pattern';
   public function __construct(){
     $this->style=<<<EOD

<style type="text/css">
body{
   padding: 0;
   margin: 0;
   background: #fff;
}

.greybox{
   float: left;
   width: 200px;
   margin: 10px 0 10px 10px;
   background: #eee;
   border: 1px solid #999;
}

.greybox h2{
   padding: 7px 0 9px 0;
   margin: 0;
   background: #ccc;
   font: bold 11px Tahoma, Arial, Helvetica, sans-serif;
   color: #000;
   text-align: center;
   border-bottom: 1px solid #999;
}

.bluebox{
   float: left;
   width: 200px;
   margin: 10px 0 10px 10px;
   background: #9cf;
   border: 1px solid #036;
}

.bluebox h2{
   padding: 7px 0 9px 0;
   margin: 0;
   background: #09c;
   font: bold 11px Tahoma, Arial, Helvetica, sans-serif;
   color: #000;
   text-align: center;
   border-bottom: 1px solid #036;
}

.yellowbox{
   float: left;
   width: 200px;
   margin: 10px 0 10px 10px;
   background: #ffc;
   border: 1px solid #c63;
}

.yellowbox h2{
   padding: 7px 0 9px 0;
   margin: 0;
   background: #fc0;
   font: bold 11px Tahoma, Arial, Helvetica, sans-serif;
   color: #000;
   text-align: center;
   border-bottom: 1px solid #c63;
}

p{
   padding: 10px;
   font: normal 11px Tahoma, Arial, Helvetica, sans-serif;
   color: #000;
}
</style>
EOD;
   }
   public function createHeader(){
     return ‘<html><head><title>’.$this->title.'</title>’.$this-
>style.'</head><body>';
   }
   public function createFooter(){
     return ‘</body></html>'; 
   }
}  

As demonstrated previously, the above "WebPage" generator class presents a few basic methods for creating the different sections of a basic web document. It also generates, via the corresponding constructor, the set of CSS styles required to build all of the content boxes that you saw before.

So far, so good right? You have learned how to build two complementary classes, that is the factory and the web page generator respectively, aimed at displaying these simple content boxes on the browser. Nonetheless, there are a few missing pieces in this schema, since the classes that render these boxes remain undefined as of yet.

Now, bearing in mind this issue, in the following section I’m going to show you the complete signatures for these brand new classes, so you can understand more easily how they can be linked with each other.

To learn how these brand new classes will be built, please click on the link that appears below and keep reading.

{mospagebreak title=Building different types of content boxes}

As I stated in the section that you just read, to complete the schema dictated by the factory pattern, it’s necessary to define some additional classes. These classes will display the complete set of content boxes that you learned previously.

Here are the corresponding signatures for these new classes. Take a look at them, please:

// define abstract ‘ContentBox’ class
abstract class ContentBox{
   private $title;
   private $content;
   abstract public function __construct($title,$content);
     abstract public function display();
}

// define concrete ‘GreyContentBox’ class
class GreyContentBox extends ContentBox{
   public function __construct($title,$content){
     if(!$title){
       throw new Exception(‘A title for the content box must be
provided.’);
     }
     if(!$content){
       throw new Exception(‘The content for the box must be
provided.’);
     }
     $this->title=$title;
     $this->content=$content;                       
   }
   public function display(){
     return ‘<div class="greybox"><h2>’.$this-
>title.'</h2><p>’.$this->content.'</p></div>';
   }
}

// define concrete ‘BlueContentBox’ class
class BlueContentBox extends ContentBox{
   public function __construct($title,$content){
     if(!$title){
       throw new Exception(‘A title for the content box must be
provided.’);
     }
     if(!$content){
       throw new Exception(‘The content for the box must be
provided.’);
     }
     $this->title=$title;
     $this->content=$content;                       
   }
   public function display(){
     return ‘<div class="bluebox"><h2>’.$this-
>title.'</h2><p>’.$this->content.'</p></div>';
   }
}

// define concrete ‘YellowContentBox’ class
class YellowContentBox extends ContentBox{
   public function __construct($title,$content){
     if(!$title){
       throw new Exception(‘A title for the content box must be
provided.’);
     }
     if(!$content){
       throw new Exception(‘The content for the box must be
provided.’);
     }
     $this->title=$title;
     $this->content=$content;                       
   }
   public function display(){
     return ‘<div class="yellowbox"><h2>’.$this-
>title.'</h2><p>’.$this->content.'</p></div>';
   }
}

As you can see, the three concrete classes shown above present the same "display()" method, which comes in useful for displaying a concrete type of content box. In addition, the classes’ constructor accepts some simple input parameters, like the title and contents that will be housed by the box in question. Quite simple, right?

All right, I believe that at this point I provided you with all the PHP classes required to dynamically display a bunch of content boxes on any web page. Since I know you may want to see how all these components can be linked with each other, in the section to come I’m going to develop an example which hopefully will show you the functionality of the factory pattern in a real world situation.

To learn more about how this practical example will be developed, click on the link below and read the next few lines.

{mospagebreak title=Displaying web page content boxes via the factory pattern}

As I explained in the previous section, a good method for demonstrating how the factory class that I defined in the beginning of this tutorial can be used to display distinct types of content boxes is to develop a fully-functional example where a sample web page is constructed and the boxes are included in its main section.

Based on this premise, below I coded a short script which performs these tasks.

Please look at the following code sample:

try{
   // create new web page object
   $webPage=new WebPage();
   // display web page header
   echo $webPage->createHeader();
   // create some content boxes
   $greyBox=ContentBoxFactory::createContentBox(‘grey’,’Title for
grey box’,’This is the sample content for a grey box that has
been created with the factory pattern.’);
   $blueBox=ContentBoxFactory::createContentBox(‘blue’,’Title for
blue box’,’This is the sample content for a blue box that has
been created with the factory pattern.’);
   $yellowBox=ContentBoxFactory::createContentBox(‘yellow’,’Title
for yellow box’,’This is the sample content for a yellow box that
has been created with the factory pattern.’);
   // display content boxes
   echo $greyBox->display();
   echo $blueBox->display();
   echo $yellowBox->display();
   // display web page footer
   echo $webPage->createFooter();
}
catch(Exception $e){
   echo $e->getMessage();
   exit();

It may be hard to believe, but the above script is all the source code required to display a sample web document that contains the three previously defined content boxes. In this case, I used the corresponding factory class to generate each of the content box objects, which are displayed on the web page via their "display()" method.

As you can see, this is a fine demonstration of how to use the neat functionality provided by the factory pattern in a real world situation. So, do you want to put this helpful pattern to work? Go ahead and try developing your own examples!

Final thoughts

Sadly, we’ve come to the end of this series. In these three articles, I showed you with numerous examples how to implement the factory design pattern with PHP 5. Hopefully, this series will contribute to expand your existing background in pattern-based programming.

See you in the next PHP tutorial!

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

antalya escort bayan antalya escort bayan Antalya escort diyarbakir escort