Search code examples
phpoopdesign-patternsfactory-pattern

Which design pattern to use to dynamically build form. PHP


I do not want to use already done library that builds forms in PHP. I want to write my own using design patterns. Im new to design patterns so I need to know which design pattern would best fit building forms dynamically in PHP.

For example so far i got something like:

 class FormBuilder {
    private $formName;
    private $formAttributes; //array('ID' => ?, 'Classes' => array(?,?) ...
    private $formStyle; //Css styling of form
    private Label $labels; //a collection of label objects holding bunch labels
    private Input $inputs; //a collection of input objects holding bunch inputs

    /* constructor to initialize everything */


   /* GET/SET methods for each of the above private variables */

   ....

   public function generateHTML() {
      //takes above information and builds HTML and returns html
   }
 }

now my problem is that i need to have an object for each label and an object for each input. Howerver i might need to have an object for or other form elements. The best way to go with this instead of having classes for each would be to use factory pattern.

Can anyone suggest a design pattern for FormBuilder and patterns to use for Label/Input or how to combine Label and Input into one class that identifies it as label or input or textarea etc...


Solution

  • You can use the Builder Pattern.
    http://sourcemaking.com/design_patterns/builder/php/1#code

    Here is a very simple example.

    <?php
    
    class FormBuilder
    {
        private $elements = array();
    
        public function label($text) {
            $this->elements[] = "<label>$text</label>";
            return $this;
        }   
    
        public function input($type, $name, $value = '') {
            $this->elements[] = "<input type=\"$type\" name=\"$name\" value=\"$value\" />";
            return $this;
        }   
    
        public function textarea($name, $value = '') {
            $this->elements[] = "<textarea name=\"$name\">$value</textarea>";
            return $this;
        }   
    
        public function __toString() {
            return join("\n", $this->elements);
        }   
    }
    
    $b = new FormBuilder();
    echo $b->label('Name')->input('text', 'name')->textarea('message', 'My message...');
    

    Outputs

    <label>Name</label>
    <input type="text" name="name" value="" />
    <textarea name="message">My message...</textarea>