开发者

zend_form: is it bad practice to load a form in init() of controller

I have a form which I need for some actions but not for others. In the actions that need it, I repeat the same code.

$form = New BlaBla_Form();

I've seen an example which declared it in init(). This means the form gets initialized even for actions that 开发者_如何学Cdon't need it. It does make the code cleaner, but is it resource intensive enough to make it a bad practice?


Try this:

  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;
      }
  }


Keyne's solution is quite nice, except the getForm() method should be protected instead of public.

Usually the presence of protected/private methods in the controller is a sign you should move them to the action helper.

However, I recommend keeping the forms together with your models:

$form = $model->getForm();
$model->fromArray($form->getValues());
$model->save();


class RegistrationController extends 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;
  }

}

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜