我有一个表单,我需要它来执行一些操作,但不需要其他操作。在需要它的操作中,我重复相同的代码。
$form = New BlaBla_Form();我见过一个在init()中声明它的例子。这意味着即使对于不需要它的操作,表单也会被初始化。它确实让代码变得更干净,但它的资源密集度是否足以让它成为一种糟糕的做法?
发布于 2010-10-28 20:56:16
试试这个:
  class RegistrationController extends Zend_Controller_Action
  {
      protected $_form;
      public function fooAction()
      {
            // ...
            if($this->getForm()->isValid()) { }
           // ...
      }
      protected function getForm()
      {
          if (null === $this->_form) {
              $this->_form = new My_Form_Registration();
          }
          return $this->_form;
      }
  }发布于 2010-10-29 03:49:31
Keyne's solution非常好,除了getForm()方法应该是protected而不是public。
通常,控制器中存在protected/private方法是您应该将它们移到操作帮助器的标志。
但是,我建议将表单与模型放在一起:
$form = $model->getForm();
$model->fromArray($form->getValues());
$model->save();发布于 2010-10-28 23:50:40
类RegistrationController扩展Zend_Controller_Action { protected $_form = null;
  public function fooAction()
  {
        // ...
        if($this->getForm()->isValid()) { }
       // ...
  }
  public function getForm()
  {
      $this->_form = (null === $this->_form)? new My_Form_Registration():$this->_form;
      return $this->_form;
  }}
https://stackoverflow.com/questions/4042761
复制相似问题