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条)

报告相同问题?

悬赏问题

  • ¥15 随身WiFi网络灯亮但是没有网络,如何解决?
  • ¥15 gdf格式的脑电数据如何处理matlab
  • ¥20 重新写的代码替换了之后运行hbuliderx就这样了
  • ¥100 监控抖音用户作品更新可以微信公众号提醒
  • ¥15 UE5 如何可以不渲染HDRIBackdrop背景
  • ¥70 2048小游戏毕设项目
  • ¥20 mysql架构,按照姓名分表
  • ¥15 MATLAB实现区间[a,b]上的Gauss-Legendre积分
  • ¥15 delphi webbrowser组件网页下拉菜单自动选择问题
  • ¥15 linux驱动,linux应用,多线程