duan0065626385 2013-03-18 18:57
浏览 93
已采纳

用于动态构建表单的设计模式。 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...

  • 写回答

2条回答 默认 最新

  • duanlu1950 2013-03-18 19:27
    关注

    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("
    ", $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>
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?