Home arrow PHP arrow Page 4 - The Singleton and Factory Patterns in PHP: Building object-oriented forms

The first approximation to object-based forms: building form element classes - PHP

Experienced PHP programmers know that web development problems are often tackled by using widely known design patterns within the context of an application. This article is the first in a series that will demonstrate how the Singleton and Factory patterns can be implemented in a real-world application.

TABLE OF CONTENTS:
  1. The Singleton and Factory Patterns in PHP: Building object-oriented forms
  2. When one is better than many: a quick look at the Singleton Pattern
  3. Object-oriented forms: applying the Factory pattern to a real application
  4. The first approximation to object-based forms: building form element classes
By: Alejandro Gervasio
Rating: starstarstarstarstar / 31
November 02, 2005

print this article
SEARCH DEV SHED

TOOLS YOU CAN USE

advertisement


The first thing to consider when developing object-oriented forms is the direct creation of the corresponding classes that generate each possible form element.

While the pillars of OOP such as Inheritance and Polymorphism strongly encourage the encapsulation of as much functionality as possible within a base class, and then the derivation of the required subclasses, in this specific case, we'll assume that a base class is not so relevant, and build directly the classes without deriving any child classes.

However, this is not applicable to all of the situations. According to the nature of the application, it's recommended to build a highly functional base class and then derive the specific subclasses, by applying some design patterns as they're required.

Based on the above explained concepts, let's start by defining the class that builds a regular text input field. Its source code is as follows:

// class textinput
class textinput{
private $html;
public function __construct($attributes=array()){
if(count($attributes)<1){
throw new Exception ('Invalid number of attributes');
}
$this->html='<input type="text" ';
foreach($attributes as $attribute=>$value){
$this->html.=$attribute.'="'.$value.'" ';
}
$this->html.='/>';
} public function getHTML(){
return $this->html;
}
}

As you can see, the class accepts an array as the unique parameter, which contains all of the attributes inherent to an input text field. Then, the constructor builds the (X)HTML markup corresponding to the element, and finally, the HTML of the element is returned by the "getHTML()" method. Indeed, the class code is extremely simple.

Let's continue defining form element classes, this time by listing the class responsible for creating radio buttons:

// class radiobutton
class radiobutton{
    private $html;
    public function __construct($attributes=array()){
        if(count($attributes)<1){
            throw new Exception ('Invalid number of attributes');
        }
        $this->html='<input type="radio" ';
        foreach($attributes as $attribute=>$value){
            $this->html.=$attribute.'="'.$value.'" ';
        }
        $this->html.='/>';
    }
    public function getHTML(){
        return $this->html;
    }
}

This class is very similar to the previous one, and implements the same logic. It accepts the element attributes as an array and builds the proper HTML code.

Because the classes are fairly understandable, let's define a few more classes, in this case for working with text areas, checkboxes and submit buttons. Here they are:

// class checkbox
class checkbox{
    private $html;
    public function __construct($attributes=array()){
        if(count($attributes)<1){
            throw new Exception ('Invalid number of attributes');
        }
        $this->html='<input type="checkbox" ';
        foreach($attributes as $attribute=>$value){
            $this->html.=$attribute.'="'.$value.'" ';
       }
       $this->html.='/>';
    }
    public function getHTML(){
        return $this->html;
    }
}

Now it's the turn of the "textarea" class:

class textarea{
    private $html;
    public function __construct($attributes=array()){
        if(count($attributes)<1){
            throw new Exception ('Invalid number of attributes');
        }
        $this->html='<textarea ';
        $textvalue='';
        foreach($attributes as $attribute=>$value){
           ($attribute!='value')?$this->html.=$attribute.'="'.$value.'" ':$textvalue=$value;
    }
    $this->html=preg_replace("/\"? $/","\">",$this->html);
    $this->html.=$textvalue.'</textarea>';

  }
  public function getHTML(){
    return $this->html;
  }
}

And finally, the corresponding class for creating submit buttons:

// class submitbutton
class submitbutton{
    private $html;
    public function __construct($attributes=array()){
        if(count($attributes)<1){
            throw new Exception ('Invalid number of attributes');
        }
        $this->html='<input type="submit" ';
        foreach($attributes as $attribute=>$value){
            $this->html.=$attribute.'="'.$value.'" ';
        }
        $this->html.='/>';
    }
    public function getHTML(){
        return $this->html;
    }
}

Okay, I think that we're armed with a set of classes handy for implementing an object-based form in a very basic way. With reference to this, below is a possible example:

// classic form generation using the form element classes
$textInput=new textinput(array('name'=>'fname','maxlength'=>'20'));
$radioButton=new radiobutton(array('name'=>'option','value'=>'1','checked'=>'true'));
$textArea=new textarea(array('name'=>'comments','rows'=>'10','cols'=>'20'));
$submitButton=new submitbutton(array('name'=>'send','value'=>'Send Data'));
echo $textInput->getHTML().'<br />';
echo $radioButton->getHTML().'<br />';
echo $textArea->getHTML().'<br />';
echo $submitButton-> getHTML();

 

Essentially, the above example builds a regular form that contains an input text box, a radio button, a text area and lastly, a submit button. Then, the snippet calls sequentially the "getHTML()" method for each instantiated object and displays the form. Although the example is rather primitive, it shows in a nutshell how easily form generation is performed.

Let's go one step further and take advantage of Polymorphism, in order to simplify the code and gain flexibility. Thus, the same example can be rewritten like this:

$textInput=new textinput(array('name'=>'fname','maxlength'=>'20'));
$radioButton=new radiobutton(array('name'=>'option','value'=>'1','checked'=>'true'));
$textArea=new textarea(array('name'=>'comments','rows'=>'10','cols'=>'20'));
$submitButton=new submitbutton(array('name'=>'send','value'=>'Send Data'));
// make array with form element objects
$elements=array($textInput,$radioButton,$textArea,$submitButton);
// display form
foreach($elements as $element){
  echo $element->getHTML().'<br />';
}
 

As you can appreciate, now the code looks much better and compact. I've built an array with the form objects, and then traversed the structure, calling in turn the "getHTML()" method to display each element.

Of course, this method doesn't offer much flexibility for the layout of each form element, but it really demonstrates that once the form element functional classes have been developed, building object-based forms is a straightforward process. Definitely, this approach presents many advantages compared to the traditional way of coding web forms.

However, we're still far away from implementing a functional "form element factory." Although we've already defined some core form element classes that play a relevant role within the overall form creation process, full application of design patterns is still out of reach.

But, you should remember that this part of the series is the first step in building a factory of form elements. There's a long way ahead, so please be patient. You won't be disappointed.

Wrapping up

After going through the first part of the series, we've learned a bit more about the basics of the Singleton and Factory design patterns, specifically aimed at being  applied to the development of a form element factory.

Also, as an introduction to object-oriented forms, we've covered one of the foundations of OOP, that is Polymorphism, to quickly implement a simple form generator application, without the annoyance of having to write the same code each time a web form must be coded on a website. 

Over the next part of this series, we'll step forward, by defining the basic structure for the form element factory, as well as its first approximation to be implemented within any PHP program. In that case, the Factory pattern will reveal its functionality when applied to a real world application. Meet you in the next part!



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