3

使用 Zend_Form 时,我发现自己创建了很多如下所示的控制器方法:

function editPersonAction()
{
   $model = $this->getPersonModel();
   $form = $this->getPersonEditForm();
   if ($this->getRequest()->isPost() {
       $data = $this->getRequest()->getPost();
       //$form->populate($data); [removed in edit]

       if ($form->isValid($data)) {
           $data = $form->getValues();
           $model->setFromArray($data);
           // code to save model then decide which page to redirect to
       }
   } else {
       $form->populate($model->toArray());
   }
   $this->view->form = $form;
}

大多数代码总是相同的,我相信有更好的方法来做到这一点。人们还使用 Zend_Form 使用哪些其他模式来减少使用的样板代码量?

4

3 回答 3

4

我喜欢尽可能多地保留在模型中

function editPersonAction()
{
   $model = $this->getPersonModel();

   if ($this->getRequest()->isPost() {
       $data = $this->getRequest()->getPost();

       if ($model->validateForm($data)) {
           // code to save model then decide which page to redirect to
       } else {
          // error management
       } 
   } 

   $this->view->form = $model->getForm();
}

那么在模型中我会有:

public function validateForm(array $data)
{    
    $form = $this->getForm();

    if($form->isValid($data))
    {
        // code to save model state

        return true;
    } else {
        return false;
    }
}

public function getForm($instance = 'default') {
   if (!isset($this->_forms[$instance])) {
       $this->_forms[$instance] = new Your_Form_Class();           
       $this->_forms[$instance]->populate($this->toArray());
   }

   return $this->_forms[$instance];
}

另外,您可以将此方法添加到所有应用程序模型都将扩展的抽象模型中,然后仅在需要执行特殊操作时才覆盖它们。

于 2009-07-03T15:04:46.393 回答
0

老实说,我的控制器中也有类似的动作。按照惯例,为了减轻控制器的重量,我要做的一件事是在模型中进行验证检查。我还从模型中调用表单对象来促进这一点(您可能已经通过getPersonEditForm控制器中的方法执行此操作。因此,如果我编写了您的操作,它将如下所示:

function editPersonAction()
{
   $model = $this->getPersonModel();
   $form  = $this->getPersonEditForm();

   if($this->getRequest()->isPost()) 
   {
       if($model->setFromArray($this->getRequest()->getPost()))
       {
           // code to decide which page to redirect to
       }
   }
   else
   {
       $form->populate($model->toArray());
   }

   $this->view->form = $form;
}

那么在模型方法中setFromArray我会有:

public function setFromArray(array $data)
{
    $form = $this->getRegistrationForm();

    if($form->isValid($data))
    {
        // code to save model state

        return true;
    }
    else
    {
        return false;
    }
}

诚然,它并不比你现有的方法简洁得多,我和你一样,经常觉得这可以更好地抽象。

于 2009-07-03T14:42:31.767 回答
0

$form->populate() 真的有必要吗?IIRC 无效表格将自动填充。

于 2009-07-03T13:43:36.633 回答