Logaholic.de

Avatar

queer as code!

Agavi vs Zend Framework Part 1 – Forms

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:

Zend Framework:

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',
        ));

        return $form;
    }

b) trigger validation in your action, use the result if validation succeeds

$demoForm = $this->getDemoForm();
$request = $this->getRequest();

if ($request->isPost())
{
    if ($demoForm>isValid($request->getPost()))
    {
        doSomeStuff();
        redirectToSuccessAction();
    }
}

c) pass the form object to your view

$this->view->demoForm = $demoForm;

Agavi:

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"?>
<ae:configurations
  xmlns="http://agavi.org/agavi/config/parts/validators/1.0"
  xmlns:ae="http://agavi.org/agavi/config/global/envelope/1.0"
  parent="%core.module_dir%/Posts/config/validators.xml"
>
  <ae:configuration>

    <validators>
      <validator class="string">
        <arguments>
          <argument>title</argument>
        </arguments>
        <errors>
          <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>
        </errors>
        <ae:parameters>
          <ae:parameter name="max">255</ae:parameter>
        </ae:parameters>
      </validator>
    </validators>
  </ae:configuration>
</ae:configurations>

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

+ Encapsulation

+ Abstraction

+ DRY

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

4. Conclusion

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).

Sources:

Bookmark and Share

Related posts:

  1. Zend Framework 1.8.0 released
  2. Zend Studio 7 and Zend Framework 1.9.0 released
  3. How we use Event Driven Development in an Agavi project
  4. Agavi chapter in the book “Quality Assurance in PHP Projects”
  5. symfony 1.1

8 Comments, Comment or Ping

  1. I’d argue that agavi does not violate the dry principle here.

    The validation definition is separate for a reason:

    - The validation may incorporate parameters that are not held in the form, but in a cookie, a header, the url or any other source. Splitting the validation up in multiple definitions would be worse.

    - The same validation definition is used for form posts, SOAP requests, XML-RPC, JSON-RPC or any other request method.

    - The same validation mechanism can be used for pure PHP templates, Tal/Metal templates, Dwoo, Smarty or any other templating engine you choose to use. How does Zend integrate with those?

    I also don’t get the point where code duplication occurs? Are you referring to the fact that agavi encourages you to create a separate error view? I’d argue that the error view serves a different purpose than the input or success view – it’s less obvious when you’re using pure HTML, but saves you a ton of work when you’re using any other response type – JSON, AJAX, SOAP, name it.

    However, I admit that I’m certainly opinionated here as I’m an agavi developer.

    Cheers

    felix

  2. “Forms are used in nearly any web application where you expect user-input.”

    This is true but it’s not the whole truth – web applications are getting more and more user input from other sources too and this is where built-in form helpers that try to do everything (output rendering, data population, input validation, data re-population, error message injecting etc.) usually start to go sour.

    I don’t know much about Zend so I’d be really interested to see how you’d handle a situation where input for an action can come from a HTML form, from another action (forwarding) or JSON. Can you still use Zend_Form? I can tell you this is easy with Agavi :)

    -veikko (a long time Agavi user and contributor and probably just as much biased as Felix :)

  3. Karsten Deubert

    @Felix:
    Thank you for your extensive comment.

    In my opinion the dry principle is broken by the need to put the raw html-code for the form in not only one view. If you wanted to change the input-names of the form, you’d have to change them in 2+n places (validation + form + any other place/view you put that form).

    I didn’t think of other output types and their validation, but you certainly have a point there. This may be an area where the encapsulation of the Zend_Form has its disadvantages – you should only use it for pure html documents (ajax too). The advantage it gets therefore, in my opinion, is its integration into *any* template engine – by using a __toString() mechanism, you just have to pass a string (which includes the whole form html and errormessages) to your view/template.

    Zend provides different classes for SOAP/XmlRpc/JSON-RPC, where you can not (without obstacles) reuse validation from a Zend_Form object.
    This is a major design difference imho, and I’d say that both approaches are suitable for different purposes.

    Btw, i don’t think my post was neutral, either ;)

  4. “In my opinion the dry principle is broken by the need to put the raw html-code for the form in not only one view.”

    That’s not true. You can reuse the html template even if you have different Input and Error views.


    //re-use Input template in FooErrorView
    $this->getLayer()->setTemplate('FooInput');

  5. @Karsten: You’re free to reuse fragments of templates via include() or require() or any other inclusion mechanism your favorite template engine offers. The same is true for validation definitions – you can either predefine and name them in a parent config or use xinclude to pull them from another config file, so given a reasonable buildup you’d have a max of 2n places to adapt. I’d not call relying on a set of names code duplication – it’s more like an interface, especially if you regard in terms or RPC request.

    Agavi validation can remap parameter names easily, so you rarely have any case where you really need to change the input names at all.

    Having the HTML-Code for the form separate from any logic is a major advantage IMHO:
    - you can have a dedicated template builder change the html at his liking as long as he keeps the parameter names. Often dedicated template builders know HTML very well, but little in terms of real programming language.

    - HTML/CSS offers all required capabilities for arbitrary complex form layouts out of the box. With a form builder you often have to modify program code to achieve a result that was not intended by the developers.

    cheers

    felix

  6. Karsten Deubert

    @Felix:

    “Templating guys” is another point where Zend_Form is lacking, in comparison, but as i said before you should keep an eye on those guys not changing the input names ;)
    Also, i don’t think we should allow “templating guys” to use evil includes/requires in templates at all.

    Without (basic) php skills one can only influence Zend forms via CSS, which sometimes may not be enough.

    Parameter remapping as principle is counter-productive imho. Yes, you can correct any bad template with PHP workarounds – but not only in Agavi ;)

    I appreciate your deep insights as a certainly more experienced agavi user :)

    @Veikko:
    Valid point.

    To conclude (again), i’d say that i personlly, for some small html-only forms, which don’t need extensive/non-standard styling, still prefer Zend_Form. I do have disadvantages for not being able to use one validator setup for multiple output types, as Agavi allows me, yes, but it fits for the project ;)

    I should add that, working without that templating guy for almost a year now, i had to create the full forms stuff for myself…

    I also didn’t want to start any religious framework-fight, dear “Agavi-Polizei” ^^

  7. Pierre

    And I think most of you are talking about obsolete problems. You know any company where the developer does not programm the forms, or at least makes the webdesigner created form a php usable form (e.g. renaming the input fields to match the scripts logic)? ;-)

  8. I use my own form generator with Agavi. It does not yet handle the validation however does reduce the leg work.

Reply to “Agavi vs Zend Framework Part 1 – Forms”