views:

60

answers:

3

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 don't need it. It does make the code cleaner, but is it resource intensive enough to make it a bad practice?

+3  A: 

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
A: 

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

}

josesalomon
+2  A: 

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();
takeshin
Thanks @takeshin. Fixed now. I've used to create getForm() method inside the controller but now I've decided to move to models. It's a pretty good ideia and I already recomeded it here http://stackoverflow.com/questions/3987532/where-does-zend-form-fit-in-the-model-view-controller-paradigma/4018185#4018185
Keyne