Zend_Form:: When should be form created in view and not in controller?

岁酱吖の 提交于 2019-12-11 00:06:17

问题


Zend_Form:: When should be form created in view and not in controller?

option 1 - form created in controller and passed to view (usually used)

controller:

$form=new MyForm();
$this->view->form=$form;

view:

echo $this->form;

option 2 - form created in view directly (looks better to me because form its subpart of view)

view:

$form=new MyForm();
echo $this->form;

Thanks


回答1:


In short: newer in view.

You may eventually:

  • create view helper for complex tasks (and call the helper in view $this->getForm()),
  • or use Model::getForm()
  • or service::getForm() when you need cross-action forms.

Further explanation:

Because in the ideal case, views contain only HTML, to separate logic from presentation (MVC).

When using TDD, you write tests for logic, never for view scripts, which are only clothes for the variables.

Displaying the form, is not only the form itself, but also checking whether it was submitted or not, checking for validation errors, setting flash messenger variables and much more.

These are too complex tasks for putting them to view scripts.

As a good exercise on separating logic and presentation, I recommend you to take a look at PHPTAL template language, which is a nice alternative to native PHP as a template language used in ZF.




回答2:


If a form appears in, say, the sidebar of a layout - like a "Subscribe to our mailing list" form - it seems reasonable to allow the view to create/render it on its own, though I'd probably do it within a view helper rather than have any new My_Form() calls in a view script. Why force every controller to deal with it?

As Padraic Brady notes in his online ZF book Surviving the Deep End: "Controllers Are Not The Data Police".




回答3:


I think the only first variant is correct, because Zend_Form is not presentation entity, but business logic entity. So it's wrong to try to instantiate it in the view. If you want simply display some form just mark up it directly in HTML - this will be much more easier for coder at least.




回答4:


Think about your team mates, are your designers( or graphical integrators ) programmers too? that approach will break down re-usability, and tasks separation.



来源:https://stackoverflow.com/questions/3248134/zend-form-when-should-be-form-created-in-view-and-not-in-controller

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!