Home arrow PHP arrow The Singleton and Factory Patterns in PHP: Building a Form Generator Class

The Singleton and Factory Patterns in PHP: Building a Form Generator Class

In this final part of the series, Alejandro Gervasio examines a point that he has not taking into consideration so far: that the layout of form elements plays a relevant role within the overall development process. With this in mind, he encapsulates the logic needed to generate web forms by defining a form generator class. This class will implement the form element factory along with all of the required form element classes.

TABLE OF CONTENTS:
  1. The Singleton and Factory Patterns in PHP: Building a Form Generator Class
  2. Object-based form generation (continued): explaining the remaining class methods
  3. A practical example: putting the “formGenerator” class to the test
  4. The source code box: listing the full developed classes
By: Alejandro Gervasio
Rating: starstarstarstarstar / 11
December 07, 2005

print this article
SEARCH DEV SHED

TOOLS YOU CAN USE

advertisement

Introduction

This is the final part of the series “The Singleton and Factory Patterns in PHP.” IN the previous article, I showed how the “formElementFactory” class may be turned into a Singleton, useful for working with a single object instance, when a program must be executed within a PHP 4 programming platform.

Also, I highlighted the advantages of using the Factory pattern to simplify tasks related to building regular web forms, by using an object-oriented approach, instead of coding them through the traditional way. Of course, the major benefit of utilizing the power of the object oriented paradigm is that once all of the form classes have been defined, generating forms within a web page is a matter of instantiating the required form objects through a factory class, and then deciding the best layout for the elements.

Stepping back to the previous part of the series, I’ve gone so far as to implement the above mentioned patterns on building object-based forms, without paying strong attention to the control of form element layout. Certainly, I wouldn’t be fully exploiting the advantages inherent in application design and code portability described throughout the series, if visual presentation is not included.

So, keeping in mind that the layout of form elements plays a relevant role within the overall development process, in this last part of the series, I’ll encapsulate the logic to generate web forms, by defining a form generator class, which will implement the form element factory together with all of the required form element classes.

With the formalities out of the way, let’s get started.

Object-based form generation: defining a form generator class

A natural place to start building object-based forms within a web page is by defining the form generator class itself. As one would expect, this class will hide the internal processing involved in instantiating form objects and expose some methods aimed specifically at giving the form a proper visual presentation. Here is what it looks like:

class formGenerator{
    // data member declaration
    private $elements=array(); // array of form elements
    private $output=''; // dynamic output
    private $elementHeader=''; // element header
    private $elementFooter='<br />'; // element footer
    private $name='theform'; // form name
    private $method='post'; // form method
    private $action; // form action
    // constructor
    public function __construct($elements=array()){
        if(count($elements)<1){
            throw new Exception('Invalid number of elements');
        }
        // data member initialization
        $this->elements=$elements;
        $this->action=$_SERVER['PHP_SELF'];
    }
    // create form code
    public function createForm(){
        $this->output.='<form name="'.$this->name.'"
action="'.$this->action.'" method="'.$this->method.'">';
        foreach($this->elements as $element=>$attributes){
            // call the abstract method formElementFactory
            $this->output.=$this-
>elementHeader.formElementFactory::createElement
($element,$attributes).$this->elementFooter;
        }
        $this->output.='</form>';
    }
    // add form part
    public function addFormPart($html='<br />'){
        $this->output.=$html;
    }
    // add element header
    public function addElementHeader($header){
        $this->elementHeader=$header;
    }
    // add element footer
    public function addElementFooter($footer){
        $this->elementFooter=$footer;
   }
    // set form name
    public function setName($name){
        $this->name=$name;
    }
    // set form action
    public function setAction($action){
        $this->action=$action;
    }
    // set form method
    public function setMethod($method){
        if($method!='post'&&$method!='get'){
            throw new Exception('Invalid form method');
        }
        $this->method=$method;
    }
    // get dynamic form output
    public function getFormCode(){
        return $this->output;
    }
}

Now that I’ve listed the source code forming the brand new “formGenerator” class, let’s break down the code to understand each relevant method.

As you can see, the class exposes the most common data members associated with a regular web form, such as “$name”, “$action”, and “$method” attributes, along with other core properties that are used to properly render form elements. The constructor accepts a single “elements” associative array, which will be passed internally to the static method “createElement()”, in order to instantiate form objects and return their corresponding (X)HTML markup.

Certainly, after the initialization tasks are performed by the constructor, the most important method within the class is “createForm()”, since it’s responsible for generating the code that renders each form element defined from outside the class. Its source code is listed below:

// create form code
public function createForm(){
    $this->output.='<form name="'.$this->name.'" action="'.$this-
>action.'" method="'.$this->method.'">';
    foreach($this->elements as $element=>$attributes){
        // call the abstract method formElementFactory
        $this->output.=$this-
>elementHeader.formElementFactory::createElement
($element,$attributes).$this->elementFooter;
    }
    $this->output.='</form>';
}

Basically, the above method builds the complete form’s code by applying the following logic: first, the opening <form> tag together with its properties are created, and second, the generation of form elements is carried out by the “formElementFactory” class. As you remember, this class was defined as abstract, so the call to its method “createElement()” is performed outside its object context. The line below shows how the markup for each element is appended to the general output:

$this->output.=$this-
>elementHeader.formElementFactory::createElement
($element,$attributes).$this->elementFooter;

Notice that aside from adding the element’s code, two additional properties, “elementHeader” and “elementFooter” are appended to the overall form’s output. The reason for adding these properties is simply to provide the class with the ability to pre-append and post-append additional HTML tags to the form element itself, allowing it to include dynamically presentational markup during the form generation process.

If this sounds rather confusing, don’t be concerned. The function of each property will become clear when I set up a functional example.

The next step in explaining how the form generator works is to analyze the rest of class methods. So, let’s jump to the few next lines to learn more about them.



 
 
>>> 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: