DRY’ing Up Your Zend Framework 2 Models with Annotations
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).
Building off the tutorial’s example, I simply delete the Form class and modify the Album model to the following.
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.
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.