PHP
  Home arrow PHP arrow Page 4 - The Singleton and Factory Patterns in PHP: Building object-oriented forms
Dev Shed Forums  
Administration  
AJAX  
Apache  
BrainDump  
DHTML  
Flash  
Java  
JavaScript  
Multimedia  
MySQL  
Oracle  
Perl  
PHP  
Practices  
Python  
Reviews  
Security  
Smartphone Development  
Style-Sheets  
Web Services  
XML  
Zend  
Zope  
Mobile Linux  
App Generation ROI  
IBM® developerWorks  
Forums Sitemap  
E-Commerce Hosting  
Linux Web Hosting  
Managed Hosting  
Small Business Hosting  
VPS Hosting  
Weekly Newsletter

 
Developer Updates  
Free Website Content 
 RSS  Articles
 RSS  Forums
 RSS  All Feeds
Write For Us Get Paid  
Request Media Kit
Contact Us  
Site Map  
Privacy Policy  
Support  
 USERNAME
 
 PASSWORD
 
 
  >>> SIGN UP!  
  Lost Password? 
Google.com  
PHP

The Singleton and Factory Patterns in PHP: Building object-oriented forms
By: Alejandro Gervasio
  • Search For More Articles!
  • Disclaimer
  • Author Terms
  • Rating: starstarstarstarstar / 29
    2005-11-02


    Table of Contents:
  • The Singleton and Factory Patterns in PHP: Building object-oriented forms
  • When one is better than many: a quick look at the Singleton Pattern
  • Object-oriented forms: applying the Factory pattern to a real application
  • The first approximation to object-based forms: building form element classes

  • Rate this Article: Poor Best 
      ADD THIS ARTICLE TO:
      error-file:tidyout.log Del.ici.ous error-file:tidyout.log Digg
      error-file:tidyout.log Blink error-file:tidyout.log Simpy
      error-file:tidyout.log Google error-file:tidyout.log Spurl
      error-file:tidyout.log Y! MyWeb error-file:tidyout.log Furl
    Email Me Similar Content When Posted
    Add Developer Shed Article Feed To Your Site
    Email Article To Friend
    Print Version Of Article
    PDF Version Of Article

     
     
    ADVERTISEMENT


    The Singleton and Factory Patterns in PHP: Building object-oriented forms - The first approximation to object-based forms: building form element classes
    ( Page 4 of 4 )



    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
     

       

    PHP ARTICLES

    - Implementing Factory Methods in PHP 5
    - Merging a File Split for FTP Upload using PHP
    - Getting Data from Yahoo Site Explorer Inboun...
    - Method Chaining: Adding More Selecting Metho...
    - How to Split a File During an FTP Upload Usi...
    - Expanding a Custom CodeIgniter Library with ...
    - Using the Yahoo Site Explorer Inbound Links ...
    - Building a CodeIgniter Custom Library with M...
    - Building an E-mini Trading System Using PHP ...
    - Completing the MySQL Class with Method Chain...
    - Building Dynamic Queries with Chainable Meth...
    - PHP Encryption and Decryption Methods
    - Building a MySQL Abstraction Class with Meth...
    - Completing a Sample String Processor with Me...
    - Mastering WHILE Loops for PHP and MySQL





    © 2003-2009 by Developer Shed. All rights reserved. DS Cluster 6 Hosted by Hostway
    For more Enterprise Application Development news, visit eWeek