Home arrow PHP arrow Page 4 - Introducing the Flyweight Pattern with PHP 5

Seeing the flyweight pattern in action - 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.

TABLE OF CONTENTS:
  1. Introducing the Flyweight Pattern with PHP 5
  2. Defining a target class
  3. Defining a flyweight factory class
  4. Seeing the flyweight pattern in action
By: Alejandro Gervasio
Rating: starstarstarstarstar / 19
February 26, 2007

print this article
SEARCH DEV SHED

TOOLS YOU CAN USE

advertisement

To demonstrate the functionality provided by the flyweight factory class that I built in the prior section, first I’m going to define a generic form generator class for constructing online forms, and then I’m going to develop an example in which all the classes are put to work together.

As you’ll see shortly, applying the flyweight design pattern will allow us to construct a basic contact form that only contains the three input fields that you saw previously. In accordance with the logic followed by the pattern in question, any attempt to create new form objects will be refused, keeping the creation of objects completely in equilibrium.

Having said that, here is the signature that corresponds to the form generator class:  

// define 'FormGenerator' class
class FormGenerator{
   private $method='post';
   private $action='processform.php';
   private $formElements=array();
   public function addFormElement(TextInputBox $formElement){
     $this->formElements[]=$formElement;
   }
   // fetch (X)HTML markup of web form
   public function displayForm(){
     $html='<form method="'.$this->method.'" action="'.$this-
>action.'">';
     foreach($this->formElements as $formElement){
       $html.=$formElement->getHTML().'<br />';
     }
     $html.='<input type="submit" value="Send Data" /></form>';
     return $html;
 
  }
}

Now that you know how the above form generator class has been defined, have a look at the following example, which builds a simple contact form by using the flyweight factory class. As you may guess, this form is comprised of only the three basic fields that I explained previously:

 // example building a web form using the Flyweight design pattern
try{
   // instantiate 'FlyweightFormElementFactory' object
   $flyweightFormElemFactory=new FlyweightFormElementFactory();
   // instantiate input text boxes
   $flyweightNameBox=$flyweightFormElemFactory->fetchFormElement
('name');
   $flyweightAddressBox=$flyweightFormElemFactory-
>fetchFormElement('address');
   $flyweightEmailBox=$flyweightFormElemFactory->fetchFormElement
('email');      
   // instantiate 'FormGenerator' object
   $formGenerator=new FormGenerator();
   // add input text objects to form generator
   $formGenerator->addFormElement($flyweightNameBox);
   $formGenerator->addFormElement($flyweightAddressBox);
   $formGenerator->addFormElement($flyweightEmailBox);
   echo $formGenerator->displayForm();
}
catch(Exception $e){
   echo $e->getMessage();
   exit();
}

As shown above, the sample contact form is built by utilizing the functionality of the previous flyweight factory class, in combination with the form generator. Logically, this process is quite simple to follow, and certainly there’s nothing special about it.

However, see what happens when I try to instantiate a new text input box, aside from the ones allowed by the flyweight factory class:

// try instantiating a different input text box (triggers an
exception)
// $flyweightNameBox1=$flyweightFormElemFactory->fetchFormElement
('postalcode');

In this case the previous script throws an exception and the program’s execution is halted. In addition, here’s another situation where I try to create two input boxes called “name.” In this case, the script returns two identical objects, as shown below:

// instantiate two identical 'name' input boxes
$flyweightNameBox1=$flyweightFormElemFactory->fetchFormElement
('name');
$flyweightNameBox2=$flyweightFormElemFactory->fetchFormElement
('name');
if($flyweightNameBox1===$flyweightNameBox2){
  throw new Exception('Input text boxes objects are the same!');
}

Now, it should be pretty clear to you how the flyweight pattern works, since in the above example only three instances of the respective “InputTextBox” class are allowed. Any other attempts to create different objects are simply rejected by the flyweight factory class.

Now, do you realize how a PHP application can control the instantiation of classes via this useful pattern? I bet you do!

To wrap up

In this first installment of the series, I introduced the key concepts of the flyweight design pattern, and showed you how to apply them in the context of a form generator application.

In the course of the final part of the series, I’m going to teach you how to apply this pattern to develop a web page generator system. I don’t think you’ll want to miss it!



 
 
>>> More PHP Articles          >>> More By Alejandro Gervasio
 

blog comments powered by Disqus
escort Bursa Bursa escort Antalya eskort
   

PHP ARTICLES

- Hackers Compromise PHP Sites to Launch Attac...
- Red Hat, Zend Form OpenShift PaaS Alliance
- PHP IDE News
- BCD, Zend Extend PHP Partnership
- PHP FAQ Highlight
- PHP Creator Didn't Set Out to Create a Langu...
- PHP Trends Revealed in Zend Study
- PHP: Best Methods for Running Scheduled Jobs
- PHP Array Functions: array_change_key_case
- PHP array_combine Function
- PHP array_chunk Function
- PHP Closures as View Helpers: Lazy-Loading F...
- Using PHP Closures as View Helpers
- PHP File and Operating System Program Execut...
- PHP: Effects of Wrapping Code in Class Const...

Developer Shed Affiliates

 


Dev Shed Tutorial Topics: