HomePHP Page 3 - Introducing the Flyweight Pattern with PHP 5
Defining a flyweight factory class - PHP
Among the considerable variety of structural design patterns that can be implemented with PHP 4 (and PHP 5, by the way), there’s one in particular that deserves special attention. It's easy to apply in the context of a given web application, and it offers remarkable functionality when it comes to preventing the unnecessary instantiation of different classes. This two-part series covers that pattern.
In accordance with the concepts that I expressed in the previous section, applying the flyweight pattern here is only a matter of defining a factory class that will be capable of returning to client code only three instances of the “InputTextBox” class that was previously defined.
In fact, this sounds like a simple thing to do, but this theory must be translated into a fully-functional class. Thus, in response to this requirement, below I defined a flyweight factory class. It obviously returns three text input objects to calling code. The signature for this brand new class is as follows:
// define 'FlyweightFormElementFactory' class class FlyweightFormElementFactory{ private $formElements=array(); public function __construct(){ $this->formElements['name']=NULL; $this->formElements['address']=NULL; $this->formElements['email']=NULL; } // return only three text input boxes public function fetchFormElement($elementName){ if($elementName!='name'&&$elementName!= 'address'&&$elementName!='email'){ throw new Exception('Invalid name for form element!'); } if($this->formElements[$elementName]==NULL){ $this->formElements[$elementName]=new TextInputBox ($elementName); } return $this->formElements[$elementName]; } }
As you can see, the above flyweight factory class exposes only one method (aside from the constructor), called “fetchFormElement(),” which is responsible for creating three instances of the respective “TextInputBox” class created previously.
But what’s the point of doing this? Well, if you use the above factory class to build a simple contact form, it always returns the same input text objects to calling code, no matter how many times the class is invoked across the same application. Logically, this prevents the unnecessary instantiation of objects that aren’t really required, in this way improving the overall performance of any application. Pretty good, isn’t it?
However, once you understand properly how the previous flyweight factory class works, there another step to make in order to demonstrate the functionality of the class in question.
Therefore, in the following section I’m going to set up a practical example that will show you how to use the previous flyweight factory class to create a basic online form that only contains three input boxes.
Want to see how this will be achieved? Okay, go ahead and read the next few lines. I’ll be there, waiting for you.