DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
Refcards Trend Reports Events Over 2 million developers have joined DZone. Join Today! Thanks for visiting DZone today,
Edit Profile Manage Email Subscriptions Moderation Admin Console How to Post to DZone Article Submission Guidelines
View Profile
Sign Out
Refcards
Trend Reports
Events
Zones
Culture and Methodologies Agile Career Development Methodologies Team Management
Data Engineering AI/ML Big Data Data Databases IoT
Software Design and Architecture Cloud Architecture Containers Integration Microservices Performance Security
Coding Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Culture and Methodologies
Agile Career Development Methodologies Team Management
Data Engineering
AI/ML Big Data Data Databases IoT
Software Design and Architecture
Cloud Architecture Containers Integration Microservices Performance Security
Coding
Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance
Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Join us tomorrow at 1 PM EST: "3-Step Approach to Comprehensive Runtime Application Security"
Save your seat
  1. DZone
  2. Coding
  3. Frameworks
  4. DRY'ing Up Your Zend Framework 2 Models with Annotations

DRY'ing Up Your Zend Framework 2 Models with Annotations

James Carr user avatar by
James Carr
·
Sep. 17, 12 · Interview
Like (0)
Save
Tweet
Share
3.60K Views

Join the DZone community and get the full member experience.

Join For Free

I’ve been using Zend Framework 2 on a recent project due to it being the department’s framework choice and off the bat one of the things that really irked me was the “Struts-ness” of how models are handled. If you walk through the ZF2 quickstart tutorial you’ll find the section on forms incredibly verbose, requiring an extra Form object and about 30 lines of boilerplate for the form’s input filter.

Luckily after digging into the documentation and source code I was able to uncover how to avoid that nonsense by using annotations. All you need as a pre-requisite is to add doctrine/common to your project (for reference, here’s my composer.json file).

{
    "name": "zendframework/skeleton-application",
    "description": "Skeleton Application for ZF2",
    "license": "BSD-3-Clause",
    "keywords": [
        "framework",
        "zf2"
    ],
    "homepage": "http://framework.zend.com/",
    "require": {
        "php": ">=5.3.3",
        "zendframework/zendframework": "2.0.0",
        "doctrine/common":"2.2.3"
    },
    "autoload": {
      "psr-0": {
        "Album":"module/Album/src"
      }
    }
}

Building off the tutorial’s example, I simply delete the Form class and modify the Album model to the following.

<?php
// module/Album/src/Album/Model/Album.php:
namespace Album\Model;

use Zend\Form\Annotation as Form;

class Album{
    /**
* @Form\Required(false)
* @Form\Attributes({"type":"hidden"})
*/
    public $id;
    
    /**
* @Form\Required(true)
* @Form\Attributes({"type":"text"})
* @Form\Options({"label":"Artist"})
* @Form\Filter({"name":"StringTrim"})
* @Form\Validator({"name":"StringLength", "options":{"min":1, "max":100}})
*/
    public $artist;
    
    /**
* @Form\Required(true)
* @Form\Attributes({"type":"text"})
* @Form\Options({"label":"Title"})
* @Form\Filter({"name":"StringTrim"})
* @Form\Filter({"name":"StripTags"})
*/
    public $title;

    public function exchangeArray($data){
        $this->id = (isset($data['id'])) ? $data['id'] : null;
        $this->artist = (isset($data['artist'])) ? $data['artist'] : null;
        $this->title = (isset($data['title'])) ? $data['title'] : null;
    }

    public function getArrayCopy(){
        return get_object_vars($this);
    }
}

Still looks pretty hideous but at least we’ve removed “some” of the boilerplate involved. The final step is to modify the AlbumController to use the AnnotationBuilder instead of the old AlbumForm.

 public function addAction(){
      $builder = new AnnotationBuilder();
      $form = $builder->createForm(new Album());
      $form->add(array(
        'name' => 'submit',
        'attributes' => array(
            'type' => 'submit',
            'value' => 'Add',
            'id' => 'submitbutton',
        ),
      ));
      $request = $this->getRequest();
      if ($request->isPost()) {
          $album = new Album();
          $form->setData($request->getPost());

          if ($form->isValid()) {
              $album->exchangeArray($form->getData());
              $this->getAlbumTable()->saveAlbum($album);

              // Redirect to list of albums
              return $this->redirect()->toRoute('album');
          }
      }
      return array('form' => $form);
    }

The only downside to this setup is that the submit button now feels a bit out of place. For this example I just leave it alone but I’d most likely encapsulate it somewhere. One option I’ve been playing with is to encapsulate the form generation in some kind of prototype builder but have omitted going that route for this simple example.

The changes I’ve made for this post can be found in my zend-skeleton project on github.

 

 

 

 

Framework Annotation

Published at DZone with permission of James Carr, DZone MVB. See the original article here.

Opinions expressed by DZone contributors are their own.

Popular on DZone

  • Distributed SQL: An Alternative to Database Sharding
  • Upgrade Guide To Spring Data Elasticsearch 5.0
  • Web Application Architecture: The Latest Guide
  • Iptables Basic Commands for Novice

Comments

Partner Resources

X

ABOUT US

  • About DZone
  • Send feedback
  • Careers
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 600 Park Offices Drive
  • Suite 300
  • Durham, NC 27709
  • support@dzone.com
  • +1 (919) 678-0300

Let's be friends: