Simplify handling of tables, entities, forms and validations in ZF2 by using annotations

If you developed any application using ZF2 you may become frustrated of the tedious work of creating boilerplate code for handling common tasks like a simple form which will be validated then saved in a database. The Zend manual recommends creating a table class, an entity class a form class, a validator class, along with the common MVC prerequisites like controller, action, view plus the Zend config stuff for paths, etc. Coming from a convention over configuration world of cakePHP this seems ridiculous.

Here is how you can speed up your workflow while still benefit from all enterprise features and flexibility you like in ZF2:

Annotations are special docblocks which store metadata in PHP classes. These information are available at runtime, unlike regular comment blocks, which are not. Note the difference:

vs

There is no support in the PHP core for annotations, but there are some engines using the reflection API which can be used successfully with annotations. Common choices are the one present in symfony and phpdocumentor. ZF2 includes support for annotation by using it’s AnnotationBuilder class and doctrine/common (a symfony package).

You can add the required package to your project by using composer:
Edit composer.json

then run
php composer.phar install

I am using a TableGateway factory to return a generic table instance or custom table instances if they exists. The table service will take care of the CRUD operations and hydrate the result set.

We start with a base entity:

To demonstrate, I will use two entities: User and Address. User contains another object called Address.
I’ve put some examples to annotate validations, filters and define how the form looks.
As you can see, the validators, filters and their options are the one shipped with Zend Framework.

Address Entity:

Basic usage

Controller action

You obtain the form from the entity with an already bound object, then work this the form as usual.

Extracting an array representation on the object including composed objects:

View – test.phtml

Here is a basic method to populate the entities with data:

You can hydrate providing an object or an array

Then you can validate your entity like this:

A very nice feature is to automatically hydrate the composed objects as well when using queries with joins. This can be done automatically if you attach this custom hydrator to the result set prototype and prepare the query for this behavior.

Any composed objects will be populated. Other joins will populate a special property called VF (from virtual fields). You can get virtual fields later by using getVF($name = null).

For example if we join ContactDetail it will populate the properties from ContactDetail as well and if we have also an aggregate expression like COUNT(*) then you will find this value in the virtual fields. The purpose of virtual fields is to store any data outside the scope of the entity.

ClassMethodsExtendedHydrator:

Then prepare the query to format the column name in order to let the hydrator to detect it.

For further reference, here is a list of available annotations:

  • AllowEmpty: mark an input as allowing an empty value. This annotation does not require a value.
  • Attributes: specify the form, fieldset, or element attributes. This annotation requires an associative array of
    values, in a JSON object format: @Attributes({"class":"zend_form","type":"text"}).
  • ComposedObject: specify another object with annotations to parse. Typically, this is used if a property
    references another object, which will then be added to your form as an additional fieldset. Expects a string
    value indicating the class for the object being composed @ComposedObject("Namespace\Model\ComposedObject") or an array to compose a collection: @ComposedObject({
    "target_object":"Namespace\Model\ComposedCollection", "is_collection":"true", "options":{"count":2}})

    target_object is the element to compose, is_collection flags this as a collection and options can take an array
    of options to pass into the collection.
  • ErrorMessage: specify the error message to return for an element in the case of a failed validation. Expects a
    string value.
  • Exclude: mark a property to exclude from the form or fieldset. This annotation does not require a value.
  • Filter: provide a specification for a filter to use on a given element. Expects an associative array of values,
    with a “name” key pointing to a string filter name, and an “options” key pointing to an associative array of
    filter options for the constructor: @Filter({"name": "Boolean", "options": {"casting":true}}). This annotation
    may be specified multiple times.
  • Flags: flags to pass to the fieldset or form composing an element or fieldset; these are usually used to
    specify the name or priority. The annotation expects an associative array: @Flags({"priority": 100}).
  • Hydrator: specify the hydrator class to use for this given form or fieldset. A string value is expected.
  • InputFilter: specify the input filter class to use for this given form or fieldset. A string value is expected.
  • Input: specify the input class to use for this given element. A string value is expected.
  • Instance: specify an object class instance to bind to the form or fieldset.
  • Name: specify the name of the current element, fieldset, or form. A string value is expected.
  • Object: specify an object class instance to bind to the form or fieldset.
    (Note: this is deprecated in 2.4.0; use Instance instead.)
  • Options: options to pass to the fieldset or form that are used to inform behavior – things that are not
    attributes; e.g. labels, CAPTCHA adapters, etc. The annotation expects an associative array: @Options({"label":
    "Username:"})
    .
  • Required: indicate whether an element is required. A boolean value is expected. By default, all elements are
    required, so this annotation is mainly present to allow disabling a requirement.
  • Type: indicate the class to use for the current element, fieldset, or form. A string value is expected.
  • Validator: provide a specification for a validator to use on a given element. Expects an associative array of
    values, with a “name” key pointing to a string validator name, and an “options” key pointing to an associative
    array of validator options for the constructor: @Validator({"name": "StringLength", "options": {"min":3, "max":
    25}})
    . This annotation may be specified multiple times.

Share This:

One thought on “Simplify handling of tables, entities, forms and validations in ZF2 by using annotations”

Leave a Reply

Your email address will not be published. Required fields are marked *