HomePHP Page 3 - Generating Web Pages with the Flyweight Pattern in PHP 5
Defining a flyweight factory class - PHP
Unnecessary and balanced instantiation of PHP classes are issues that can be easily solved by using the flyweight design pattern. If you want to learn more about it, you should start reading this article. Welcome to the final part of the series “Using the flyweight pattern with PHP 5.” As you may have guessed, this series walks you through the implementation of this helpful pattern with PHP, and shows you how to apply it in concrete cases.
To develop a web page generator system capable of maintaining balance with the number of DIV objects created across the application, I must first define a flyweight class. This class will be provided with the capacity to return only three DIVs to client code, identified as "diva","divb", and "divc" respectively.
Naturally, in accordance with the logic that stands behind the flyweight pattern, this factory class will refuse any attempts to create more DIV objects, in this manner keeping in equilibrium the number of objects used by the web page generator application.
Now that you know how this flyweight class is going to work, I'd like you to pay attention to its signature, which is listed below:
// define 'FlyweightDivElementFactory' class class FlyweightDivElementFactory{ private $divElements=array(); public function __construct(){ $this->divElements['diva']=NULL; $this->divElements['divb']=NULL; $this->divElements['divc']=NULL; } // return to calling code only three DIVS public function getDivElement($divId){ if($divId!='diva'&&$divId!='divb'&&$divId!='divc'){ throw new Exception('Invalid ID attribute for DIV element!'); } if($this->divElements[$divId]==NULL){ $this->divElements[$divId]=new DivElement($divId); } return $this->divElements[$divId]; } }
You can see that the above flyweight factory class has one relevant method, called "fetchDivElement()," which is responsible for controlling the number of DIV objects that will be returned to client code. As one would expect, if an invalid $divID argument is passed to this method, an exception will be triggered, and program's execution will be stopped.
At this stage, hopefully you'll have a much better idea of how the previous flyweight factory class does its business. So, provided that my assumption here is correct, it's time to move forward and see how this class can be put to work to generate dynamic web pages that include only three DIV elements.
The experience sounds interesting, therefore if you wish to learn how the previous flyweight class will be used to create web documents on the fly, please jump into the following section. Don't worry, since I'll be there, waiting for you.