Agavi and Zend Framework are two major MVC PHP5 Frameworks today. I am actively using both in two different projects.
I will discuss some differences, starting with Part 1 now: Forms.
Forms are used in nearly any web application where you expect user-input. Following the “never trust your users” rule, proper validation is one major (security-) subtopic of forms.
1. Building simple Forms:
a) define your Zend_Form object, once, including validation
* @return Zend_Form
protected function getDemoForm()
$form = new Zend_Form();
$form->addElement('textarea', 'comment', array(
'label' => 'comment:',
'required' => true,
'validators' => array(
array('StringLength', array(160), array(1))
$form->addElement('submit', 'submit', array(
'label' => 'submit',
b) trigger validation in your action, use the result if validation succeeds
$demoForm = $this->getDemoForm();
$request = $this->getRequest();
c) pass the form object to your view
$this->view->demoForm = $demoForm;
a) write html code for your form in your view
You know how that works. (Or see the Agavi documentation link below)
b) add validation to your write-action
The Agavi documentation prefers defining validators in a .xml file, per action, app/modules/Posts/validate/Add.xml: (module Post, Action Add)
<?xml version="1.0" encoding="UTF-8"?>
<error>The title field has an invalid value.</error>
<error for="required">Please provide a title.</error>
<error for="max_error">The title must be shorter than 255 characters.</error>
c) formpopulationfilter magic
“All we need to do is re-display our form on the error page and the AgaviFormPopulationFilter will perform all of those duties. To re-display the form we could either include it in the ErrorViews template or we could set the input template in the view.”
2. The Zend Framework way
3. The Agavi way
- I have to keep an eye to input names, as they are needed at more than one place. Beware of templating guys changing the input names, breaking stuff.
- validating an action, not a single form/form object
- breaks the DRY principle, code duplication occurs
I prefer Zend Framework over Agavi for forms. The main reason is the encapsulation in ZF with the Zend_Form object.
I can have more separated forms with separate validation on one page. I can reuse forms withouth having (that much) duplicate code anywhere. I don’t have to make changes to multiple locations if changing input names or validation, just one object holds every needed information/configuration. Zend_Form also does the html output for me, application-persistent interface guaranteed (styling is done via css or decorators per form/element).