A Blog Application Part 1 – Working with Doctrine 2 in Zend Framework 2

This will be the first part of a longer series in using Doctrine 2 in a Zend Framework 2 application. We will be building a very simple blogging application, making use of the most common use-case-scenarios for Doctrine 2. The way i see it right now, most people are interested in the basics of using the ORM in Zend Framework 2 correctly. Examples for use-case-scenarios like @OneToOne, @OneToMany and @ManyToMany are missng and even setting up the Zend\Form and the specific Hydrators correctly still remain a little mystery to some (even to me!).

In this first part we will be building a simple entity for our posts. We will be building a form to add, edit and delete our post entity. We will not cover any relationships in this first example, as this simply is too big for a single blogpost.

This post has been outdated. Please see the DoctrineModule-Documentation for further details

The concept

First of all i assume that you guys have successfully integrated Doctrine 2 into your Zend Framework application. If this is not the case please visit my Blogpost and start integrating Doctrine 2 first.
As mentioned before, we will build a simple blogging application. For this we will do the following things:

  • Create a new Module named Blog
  • Create new routes for our module
  • Create a controller for our posts stuff
  • Create two forms for the following purposes (add, edit, delete)
  • Manage Database interaction via Doctrine 2

Are you ready to start? I am, so let’s continue…

Creating the new Module

To start our new Module create the following folder- and file-structure in your Zend Framework 2 appliction:

As everything will be running within the namespace Blog we need to make this namespace known to the Zend Framework 2 application. For this edit the the following file to given content:

Next thing to do is to edit the Module.php. Nothing too special here, basic configuration stuff.

Current status
If now we call our application with our wanted route e.g. http://blog.loc/post we will be welcomed with the following message:

The requested URL could not be matched by routing.

We haven’t done the required routing yet, so let’s go ahead and do that now. Edit ./Blog/config/module.config.php. The highlighted lines are the relevant ones (the ones where usually the copy and paste errors happen).

Status Update
If you call http://blog.loc/post now, you’ll be granted following message:

The requested controller could not be mapped to an existing controller class.

And this is good, it simply tells us that we shouldn’t slack off and start creating our controller class now.

Creating the Controller

Since all that’s missing for the SetUp is a Controller, let’s create this. Open the ./Blog/Controller/PostController.php and modify it with the following content.

Another StatusCheck
As long as you have created all files and followed the instructions in this tutorial, you should now be presented with an empty site calling http://blog.loc/post (or not empty, in case you have modified index.phtml alrady)

Creating the Doctrine 2 Entity

Since we have the basic structure of our Zend Framework 2 Blogging Application in place it is now time to define and create our Doctrine 2 Entity. Since we will only be covering the basics for now, our Entity will look like the following:

  • Entity name: Post
  • Property ID: Primary identifier
  • Property TITLE: Title of our Blog Post
  • Property TEXY: Content of our Blog Post

And for the start this is all. We will cover Tags and Author relationships within future Blogposts, but for now this is enough. So let’s start creating our Entity. Open ./Blog/Entity/Post.php and modify it given this content:

Take careful not of all the @ORM\Annotations! This is how Doctrine 2 works. The Setter- and Getter-Methods are pretty basic, no need to go into detail for those.

Above line 15 we first define that this class represents a Doctrine 2 Entity. We tell Doctrine 2 that our tableName will be “posts”.

Inside of the class we define the properties. Notable here is the definition of the primary key using the @ORM\Id and @ORM\GeneratedValue Annotations.

The Database

Since Doctrine 2 is an all around Framework, we can potentionally use the command line to create the database table based on this Entity-Class. Personally though i simply don’t have enough knowledge to do so, i create the database manually given following script.

To get our indexAction() running directly, let’s create one simple entry to this table manually, too.

The Index Overview

Since now we have our Database ready, we can start to work with Doctrine 2s EntityManager. Before working on the indexAction() we need to add something to our Controller. This is what my controller looks like now:

What happened here? Well, this is pretty simple. We add a property to our Controller called $entityManager. This basically is the glue between our EntityModels and our Database. We have defined the Service Doctrine\ORM\EntityManager while setting up Doctrine 2 for Zend Framework 2 and now make use of it. If you work with Entities in multiple Controller and always use the same EntityManager i suggest extracting these function into a separate Controller-class from which you can extend your Controllers from. Given Example, personally i created a EntityUsingController which extends the AbstracActionController and my PostController extends the EntityUsingController. It’s to keep my code clean and separated and makes each class only worry about the things they need to.
But enough talk, we have set this up now, let’s create our indexAction()!

This will fetch all current posts from the database and assign it to the view variable ‘posts’. To be able to view all Posts now we need to create our view, for this we edit ./Blog/view/blog/post/index.phtml

There’s not too many things happening here. We set the Title for this page, we give it an ‘add’ links, as well as edit and delete links for each post stored in our database. Feel free to modify the output as desired… Looking at the page now you should see one Blogpost, the add-links to http://blog.loc/post/add as well as the edit- and delete-link to http://blog.loc/post/(edit|delete)/1. In case of the urls not being displayed as desired, check back at the routing setup of this blogpost.

Setting up the Form

Before we go into details of the addAction() we first define our formular. For this we will be using a Form and a Fieldset. Why both? Because for later use with relationships this will become our standard way of doing things, so we may as well use the little ‘advanced’ method for our basic purposes, too.
If you have not yet looked too much into detail of Zend\Form or Zend\Form\Fieldset i strongly suggest you reading about Zend\Form Features of Zend Framework 2 at Michael Gallegos Blog. He explained it very well and ten times better than i possibly could…

Let’s start by creating the Fieldset first. The fieldset will hold the information required for a post. This is the ID (for editing purposes), the title and the text. Since we’re working on a Fieldset we will also include an Interface to be able to define our filtering- and validation-rules in there.
I will give you the code now and then we will go over it step by step, as there’s a lot of things happening here.

WOW, let’s go over this now. First let’s have a look at the use statements. We include our Entity\Post to be able to bind the form data to our Entity later. Then on line 6 we include Stdlib\Model\Registry. This is a SingletonRegistry-Class i wrote in a separate namespace. You need to do this, too. Not really in a separate namespace, but it makes a lot of sense there. We use this Registry class to ‘transfer’ the EntityManager from our Controller down to the Fieldset. Right now this is the simplest and cleanest solution to do this – certainly not the best, but we will have to wait for the ZF/Doctrine Devs to come up with a better solution to do this.

We need the EntityManager for the DoctrineEntity-Hydrator. This is the Hydrator we include on line 11 and i used to map form data to doctrine entities.
Next to that we use the Fieldset and InputFilterProviderInterface. The later is used to tell the Form on where to find our inputFilters and Validation-rules. This is where the getInputFilterSpecification() function comes into play. Simply take a look at it and i am sure you get a grip on how it works.
The next interesting lines are 22 and 23. This is where we actually set the Hydrator for our form and give it the EntityManager (therefore the Registry) and we set the Forms Object to a new Post(). This tells the form that we’re actually submitting data. The DoctrineHydrator then grabs all Forms Data and hydrates it into the Form Object.

Once again, if my explanation seems a little vague, i strongly suggest Michael Gallegos blog article about it.


The PostForm is a little simpler to understand than the PostFieldset. We Add some basic elements like a submit-button and a Cross-Site-Request-Forgery-Protection, we add the PostFieldset and we tell the Form what to validate with the setValidationGroup(). The rest should be pretty simple to understand.

Displaying the Form

Let’s quickly check if we have done everything correct. Modify our controllers addAction() with the following content and remember to include the required classes:

Nothing much happening here yet. We get the EntityManager and set it inside the registry, call an empty Post(), the PostForm(), bind the Post to the Form and return the form to our view. So let’s display the form now. Edit ./Blog/view/blog/post/add.phtml

Nothing too special here, pretty standard stuff. Only thing notable is don’t get confused by $form and $this->form(). $form is my assigned view Variable and is the Zend\Form essentially. $this->form() is a ViewHelper to render Form-Specific stuff. And that’s it.

Call your application and see if the form get’s displayed (it should).

Saving Doctrine 2 Entities

Let’s now take a look at the final addAction() and how to save the Doctrine 2 Entities to our Database. To sum it up what we have to do:

  • First we initiate the form and the entity
  • Then we check if the form is already posted
  • If its posted, the Post data is bound to the form
  • Then the form gets validated
  • If it’s valid the entity should be saved
  • And let’s get redirected to the index on success

A couple of lines to describe things but not even many more lines to do it. Here we go:

Fill out the form, send it and you will have your entity saved to the database. You will notice that the Entities are sorted by their ascending ID. If you want to change this behavior check our the Doctrine 2 Manual on how to do that :) Manuals are fun!

Editting Entities

After having our entities added to the database, the next logical step is to edit them because we made a spelling mistake, like there probably are numerous in this post :(

For this we do not need to change our form at all. We don’t even need to change our view, other than to copy this inside the edit.phtml and change the title to edit instead of add. The main thing different is the controller part. Here we first need to get the actual entity before editing. Here is the controller and the view:

Test this by using the edit links of your index view and you will be able to edit your entities.

Removing Entities

Removing of Entities is pretty simple. I will simply give you the EntityManager-Snipplet required, but of course you should build a form around it, asking for a removal confirmation, etc… :)

Hardcore removal, only for experts! :P

Final Conclusion

Using bare data-models / Entities and save them to the database using Doctrine 2 is a pretty simple task. The additional hassle we did here with the Registry Class will come in handy later.

I hope that i will be able to give you tutorials using relationships as soon as possible. Current standing of the DoctrineORMModule however doesn’t allow me to edit my Entities using relationships without errors. I’m sure it won’t last too long for until those get fixed. If it lasts a little too long, i will at least display the possibilities to ADD Entities to the database that contain relationships, as this part works.
Until then i wish you all a great time using Zend Framework 2 and Doctrine 2 together.

87 Responses to A Blog Application Part 1 – Working with Doctrine 2 in Zend Framework 2
  1. gudik Reply

    $id = (int) $this->params(‘id’, null);
    if (null === $id) {
    return $this->redirect()->toRoute(‘post’);

    don’t work =)
    $id = (int) $this->params(‘id’, null);
    $id – always int.
    $id null !

  2. Hn Reply

    tahnk you very m uch pf this exemple, Please my edit and delete don’t work :/ the id that i get is always null ??

  3. Hn Reply

    Hi, Please help me….
    i have o big problem with the class association i don’t know how to create their entities !!
    also i want an exemple for adding class that contain foreign key.
    thank you

  4. Villers Reply

    Hello Sam!

    1st of all, thank you for your tutorial, it really got me on my way working with zend and doctrine.

    I went through your updated example on https://github.com/doctrine/DoctrineModule/blob/master/docs/hydrator.md#a-complete-example-using-zendform and had to switch between those two examples to get it going.

    But now I am stuck at the “edit” part. You refer to property “userService” that has to be part of the AbstractActionController, which it is not. You use that for what? Finding the corresponding id in the database? With the example on this site here it looks good and “right” to me. So what’s the difference?

    Thank you again for introducing me to ZF2/Doctrine!

    cheers mate

  5. Iyngaran Iyathurai Reply

    I see this line – use Stdlib\Model\Registry; in this example. where is the code for that Stdlib ?

  6. daslicht Reply

    Thank you !

    The Link to : ” Michael Gallegos Blog. ”
    is broken

    • Sam Reply

      Hey, it’s that french dudes fault for changing his URL :D Just cut the /blog and you should be fine, I’ll fix this later though, thanks for pointing it out ;)

  7. Inoelkis Reply

    @Sam Your post is very good. I’m new in Zf2 and trying to use it has been having some trouble with the use of github and cant not download succesfully de modules.
    I’m wondering if you can share the full application to me(all the proyect) or send to me for e-mail to keep learning.
    I hope that this not be a trouble for you.

    • Sam Reply

      Just download all the Zip-Files and set up the autoloading. Autoloading stuff can be found via google ;)
      But i strongly suggest you get composer and git running on your system. Soon nothing will go without that anymore :D

  8. Marcus Reply

    When i have a DropDown woh’s filled through a Doctrine-Relation, the Entity has only the teamname-Field, but not the ID from the DropDown.

    // Fieldset
    'name' => 'lokale_id',
    'type' => 'DoctrineModule\Form\Element\ObjectSelect',
    'options' => array(
    'label' => 'form.team.lokal',
    'object_manager' => $oObjectManager,
    'target_class' => 'Teams\Entity\Lokale',
    'property' => 'label',
    'empty_option' => '-- auswählen --'

    Thats my Entity after Post is send:

    Teams\Entity\Teams Object
    [id:protected] =>
    [users:protected] => Doctrine\Common\Collections\ArrayCollection Object
    [_elements:Doctrine\Common\Collections\ArrayCollection:private] => Array


    [teamname:protected] => FooFighters
    [lokale_id:protected] =>
    [lokal:protected] =>
    [day:protected] =>

    Any Ideas?

    • Marcus Reply

      okey, i have the error :-)
      the Setter from the Entity was wrong.
      But why my Entity can’t be saved???

      An exception occurred while executing ‘INSERT INTO teams (teamname, lokaleId, day) VALUES (?, ?, ?)’ with params [“FooFighters”, null, null]:

      SQLSTATE[23000]: Integrity constraint violation: 1048 Column ‘lokaleId’ cannot be null

      But the Entity has the lokaleId with Value 1

      if($oTeamForm->isValid()) {
      #echo "

                      #echo $oTeamsEntity->getLokaleId();die;

  9. neetin Reply

    Hi Sam,

    Thanks for your tutorial. I got one error when setting hydrator.

    Here is the error:

    An error occurred
    An error occurred during execution; please try again later.

    File: Doctrine\Common\Persistence\Mapping\MappingException

    Message: Class ” does not exist

    Here is my model class:

    setHydrator(new DoctrineHydrator(new DoctrineEntity($objectManager)))
    ->setObject(new Assigned());

    Please help me to get rid of these error. Thanks

    • neetin Reply

      Also I did not find this class: Stdlib\Model\Registry
      anywhere in this tutorial.
      Could you please post the content of this file, or any alternative to pass entity manager to the forms.


      • Sam

        As pointed out in the post, it’s outdated – please see the first section of the post again.

    • Sam Reply

      As pointed out in the post, it’s outdated – please see the first section of the post again.

  10. philippe 40 Reply

    Hi Sam,
    Thank you for this very useful link : DoctrineModule/docs/hydrator.md.

    Now I need an advice.
    I have two fields in my form : ‘firstname’ and ‘lastname’ but in my db, they are concatenated in one field (‘name’).
    How to do that on the base of the example of the link above ?

    I’d like to keep the ‘bind’ feature and the following :
    ‘type’ => ‘DoctrineModule\Form\Element\ObjectSelect’,
    ‘name’ => ‘name_select’,
    ‘options’ => array(
    ‘label’ => ‘Names list’,
    ‘object_manager’ => $this->em,
    ‘target_class’ => ‘Cine\Entity\Name’,
    ‘property’ => ‘name’,
    ‘empty_option’ => ”

    Is it possible ?

    Thank you

  11. bhuvanesh Reply

    Class ‘Stdlib\Model\Registry’ not found in C:\wamp\www\zend2doc2\module\Blog\src\Blog\Controller\PostController.php on line 49

    I don’t knw how to solve…..
    would any one help me…

  12. Kamy Reply

    Hi Sam!

    Your articles have been a great help for me when I started working with ZF2 :). Thanks for the great work you put into it!
    It seems now I have reached a dead end trying to edit a form which contains fieldsets and maybe you have a suggestion on what could be the cause. So I store the data in db, relations seem to be good so far. Then on edit form it returns 2 fieldsets of a given kind (in db I have 2 records for these 2 fieldsets, so this is good) but there are no values in fieldsets… The object is bound to the form, main fieldset is populated, but fieldsets it contains, for some reason are not.. If you could give me a hand or have any idea on what might be wrong I would really appreciate your help :) Thank you!

    • Sam Reply

      Hey Kamy, forms are a bitch… usually this kind of error happens for a) wrong hydrators or b) wrong basedata / fieldset names (again tied to hydration). I can’t really give too much tips when it comes to that other than to debug and see what actually happens :S

  13. Andrew Starlike Reply

    Fatal error: Class ‘Stdlib\Model\Registry’ not found


    Damn, i just cannot find a tutorial with working code!!!! So frustrating!

    • Sam Reply

      Hey Andrew, let me help you with something against your frustration:


      In the “docs” Folder you’ll also find the file “form-element.md”, which will be used to create like a drop-down list for categories or the likes. Actually all documents in there will be incredibly helpful to you! ;)

      • Vitor

        This is what I’m looking for, but I really think it’s very difficult to do something as simple zend, he was supposed to make our lives easier, not hinder.

      • Sam

        That depends on the knowledge i guess. Actually ZF2 is VERY StraightForward. But i do agree that there’s a HUGE lack in great tutorials n the likes.

        ZF2 Forms are actually VERY awesome and the implementation of Doctrine is very neat, too

      • Andrew Starlike

        Thanks a lot Sam, that was exactly what i needed! Here comes another coding night…
        look, i hope my rude (first) comment doesn’t bother you, i was just extremely angry.

      • Sam

        No worries, I’ve had worse and i know outdated stuff sucks, but I’m far too lazy lately :]

      • Vitor

        Hey it worked perfectly with the link that you passed.

        But now i have the relation, and i have the type of the field like this:

        $categoriaFieldset = new CategoriaFieldset($objectManager);
        ‘type’ => ‘Zend\Form\Element\Collection’,
        ‘name’ => ‘categorias’,
        ‘options’ => array(
        ‘count’ => 2,
        ‘target_element’ => $categoriaFieldset,

        And i want to make this to be a DoctrineModule\Form\Element\ObjectSelect, but how can i populate it with the categories?


  14. Vitor Reply

    Hi, it’s cool, but how can you add a categorie to the post?, how it would work with combobox or checkbox as wordpress? i know how to make a crud, but not with categories, example if is the action edit to populate the combobox with the categorie of a post

  15. Łukasz Reply

    Hi, one question about this example. Do you have any way to use bind() with entities that use magic methods (__set and __get)?

    • Sam Reply

      Hi, as far as i know that doesn’t work because of thw way doctrine is creating the proxy classes which need concrete methods. But dont take this for granted, people in #doctrine may know better.

  16. Angusfr Reply


    i would like to know how can you use the findAll() function on a repository because i can’t do it at all :'(

    i can find one object using this :
    $album = $this->getEntityManager()->find(‘Album\Entity\Album’,’1′);

    but when i use this, 100% fail :
    $album = $this->getEntityManager()->getRepository(‘Album\Entity\Album’)->findAll();

    Zf2 can’t find the findAll() function but he find the find() function my entity manager.

    Someone can explain me this please ?

  17. Some Mistake Reply

    can you help me Sam? I can’t find any solution in the internet about this…

    i have login fieldset:
    ‘type’ => ‘Zend\Form\Element\Email’,
    ‘name’ => ‘email’

    ‘type’ => ‘Zend\Form\Element\Password’,
    ‘name’ => ‘password’,

    Then, I added it into the login form:
    $loginFieldset = new LoginFieldset($serviceManager);

    In controller I bind form and entity:
    $form = new LoginForm($this->serviceLocator);
    $user = new Entity\User();

    but in my view, i can’t echo rows of the form:
    $this->formRow($form->get(‘email’)); <- it shows: Catchable fatal error: Object of class Zend\Form\View\Helper\FormRow could not be converted to string in …

    Can you give any suggestions?

    • Sam Reply

      I may be wrong, but isn’t it that even on the basefieldset you still need to access it first? Like


      Check the HTML-Sources to see what fieldnames they actually have ;)

      • Some Mistake

        U a genius!) So fast and so right!) Thanks!

  18. nomen Reply

    Hey Sam!
    I’m very appreciate you for writing this article!
    But maybe you could show your Registry class (on github gist for example) and describe where exactly did you placed it?
    It’s will be very helpfull for me and others.

    • Sam Reply

      This part is actually very outdated :S You are to use the ServiceManager to do this kind of stuff. Please refer to this Blogpost to see about the details.

  19. nomen Reply

    Hi everyone.
    I’ve stopped at “the index overview” because of error. It says that:
    “The class ‘Blog\Entity\Post’ was not found in the chain configured namespaces …”

    And it was because of at the
    ./Blog/config/module.config.php file in article example were no the doctrine config (at 34th line). I’ve added such code:

    and everything start working correctly.

    • Sam Reply

      Yep, you definitely need that. This however has been pointed out inside the article, where i linked my other blog post about how to set up Doctrine for your projects ;) Thanks for clarifying it for the others though! ;)

      • nomen

        Ah, you right!! :))
        Btw, your links at “the concept” part is pointing now to the current article, not to “installing doctrine 2 …” ;)

  20. Simon Reply

    Dit you try the hydrator on an object with an many-to-one relation? Works fine for me until the relation value should be null. Do you have any clue on this?


  21. Billy Scholtz Reply

    Thank you for your blog. Without it, I would have struggled a lot to get going in ZF 2. Bought all the books(3 of them) none as current on ZF2 as your blog.
    Please keep up the good work.

  22. Jack Reply

    One problem more I have. Registry::set(‘entityManager’, $em); not working in my controller in add action..(I have use Stdlib\Model\Registry namespace in PostController) I’m getting HTTP 500 error and this is a reason:
    PHP fatal error: Class “Stdlib\\Model\\Registry” not found.

    • Sam Reply

      The Registry-Stuff is outdated. I will follow up on that topic in approximately 2 weeks, until then please refer to https://github.com/doctrine/DoctrineModule/blob/master/docs/hydrator.md#a-complete-example-using-zendform

      Apart from that, it’s ‘Yourmodulename\Stdlib\Model\Registry’ ;)

    • Jack Reply

      Thanks again for your help. Changing this lines in fieldset class resolved issue:
      use Zend\Stdlib\Hydrator\ClassMethods as ClassMethodsHydrator;

      $this->setHydrator(new ClassMethodsHydrator(false))
      ->setObject(new Post());
      help me and form starts working. For what we need this hydrator from DoctrineEntity & EntityManger here if it working fine with ClassMethodsHydrator? Setting hydrator as DoctrineEntity gives us anythink better? I’m newbie sry if my questions are so lame :P

  23. Jack Reply

    this tutorial not working for me:

    404 Not Found

    The requested URL /zf2test/ZendSkeletonApplication/public/blog/ was not found on this server.

    Can you send full code of ./Blog/config/module.config.php?

    • Sam Reply

      Hey, the requested URL appears to be fully qualified. This implies that you did not set-up the VirtualHost for your project.
      If you carefully follow all the instructions in the Blog-Article, you will have a working Solution. I suggest you start checking for errors at the very beginning of installing the ZF2-Application.
      The config you’ve requested is pretty much visible apart the doctrine-configuration. That post is linked, too.

      • Jack

        Thanks for your answer Sam. Hmm.. but it means that ZF2 apps will not work on relative paths? Application module works fine so new created module should too I think.. In my opinion host shouldn’t be “condition” to work, it should be only an option. I wanna to make flexibly app which I can just put in folder and work from relative URL on the server or link to domain or host if I rly need it.

      • Sam

        I’m sure it works relatively, too, but i have no clue about those error messages in there. Biggest suggestion would be: is your module registered in application.config.php? From there check the route, the controller, the action, the view file.

      • Jack

        Yes module is set in config file, other files are correct too controlers etc. But in my project now working only this http://serwer/zf2test/ZendSkeletonApplication/public. Nothing more for example i cannot use http://serwer/zf2test/ZendSkeletonApplication/public/application or http://serwer/zf2test/ZendSkeletonApplication/public/application/index etc. I’m getting 404 error. I have clean Zend skeleton project and integreted doctrine only from your blog post.

      • Sam

        Sounds like .htaccess file isn’t working. :S Can’t help out too much with that though :(

      • Jack

        I have server on VirtualBox with debian. I’m working on win7. I setup host and now http://zf.dev/post/ is working fine for me, htaccess working too so i don’t understand why it wasn’t work by relative path :|. Btw how now and where I can set blog route? I wanna to call just module blog and http://zf.dev/blog/ should display http://zf.dev/post/index action.

      • Sam

        Routes are inside module.config.php Check the manual for differences between literal and segment routes, as well as what exactly a child-route is.

      • Sam

        The Registry-Stuff is outdated. I will follow up on that topic in approximately 2 weeks, until then please refer to https://github.com/doctrine/DoctrineModule/blob/master/docs/hydrator.md#a-complete-example-using-zendform

  24. Mateusz Reply

    Sam, thank you for great tutorial and devoting you time for writing a post. We wait for the next :)

  25. Mosak Reply

    Hi Sam,
    You said about “Stdlib\Model\Registry”:
    “Hi there, it’s not a Zend-Class. By the time of writing that code, there was simply no other elegant solution to get the Doctrine EntityManager down to several Fieldsets. Looking over at Github now there appears to be a way which i will cover sometime in the future, too.”
    Please tell what is the other way:) Thanks in advance.

  26. Michael Reply

    Hi Sam, thanks for explaining how to install doctrine in zf2 and how to use it. Everthing works fine, except the Stdlib\Model\Registry.

    The class Stdlib\Model\Registry is not available in my zend\stdlib repository. Is there another solution or can you post the class?

  27. Adil Reply

    Hi Sam, thanks for taking time to publish these very helpful articles which will help many newbies like me.
    I have some very silly basic questions about complicated arrays.

    I am unable to fully understand so many multi-dimensional arrays in module.config.php. Is there any graphical representation or a detailed explanation or documentation about what these all arrays are about ?

    How one can manage to avoid making mistakes in these arrays while making any new addition ?

    May be you can refer to any existing helpful article which explain in detail about the structure of these arrays. I hope you will help me.

    • Sam Reply

      This pretty much boils down to experience, a good IDE, and at first a good coding style. Always intend a level of a multi dimensional array. Basically each new dimension will be introdudes as ‘key’ => array(/** new dimension */). A list of all possible keys i don’t have myself, but i’ll try to make a little more basic blog about this possibly sometime in the future.

      • Adil

        Thanks Sam for your response. One more question from your above mentioned code about /Blog/config/module.config.php:

        Why you inserted ‘post’ => array(
        ‘routes’ => array(
        ‘type’ => ‘segment’,

        Can we insert it at any point for example AFTER
        ‘options’ => array(

        If not then why not ?

        I hope you will again answer my question.

      • Sam

        Basically you have to read this part like this: Configuration -> Router configuration -> Route-Name -> Type-Configuration -> Additional Type Options, etc…

        Maybe you’d be well suggested reading something more about arrays in general? If you have trouble understanding this, then underlying features of ZF2 will be quite a few miles away for you :(

  28. dunpeal69 Reply

    Just a note about database schema generation with Doctrine 2 CLI (don’t know if someone is interested by this information but I didn’t saw that in this interesting article) :

    I’m using latest version of ZF2 and Doctrine2 plugin by cloning them from their respective git repositories and I tried today :

    Then it has automatically created the associated tables for my model

    I hope this can help someone.

    • Sam Reply

      Thanks for the hint. This is certainly something very useful and i will check this out and probably dedicate a post for this. Model first is a development approach i highly appreciate!

  29. Tommy2002 Reply


    I would be interested how to use Zend 2 and Doctrine 2 can access two databases. Can someone help me?

    Thank you


    • Sam Reply

      Take alook at the doctrine configuration in my previous post. Basically if another module needs another connection, you’d simply change the connection driver for that module. I haven’t done this, but shouldn’t be too difficult, i may suggest you trying to ask in either #zftalk or #doctrine at freenode.ned IRC

  30. Bba Reply

    Hi Sam,
    Thanks for the tutorial, It helped a lot
    However you have a typo error in your delete post
    Am guessing it should be

    Good one bro, keep up the good work
    God Bless!!!

    • Sam Reply

      Thanks for the hint, fixing it asap. You may also be interested that very soon (i.e. roughly a week from now) i’ll be redoing this series with little more clean code ;)

      • Bba

        will be looking forward to it

  31. Mukoro Godwin Reply

    Every thing on the zend framework site is confusing but with your tutorial my zf2 is running. Thanks so much for sharing I would keep following

  32. Máté Kocsis Reply

    Hi Sam!

    Your tutorial helped me a lot, but now I am facing to a serious problem.

    When I call $form->getData() after the form is submitted, it shows that only the two date fields have value, neither the id, nor other collections and associations (e.g. the ‘author’ select field which is a foreign key in my table)… Could you give me some hint? It seems so weird that some fields have value, and the most of them don’t.

    I followed your and Michael Gallego’s instructions to create the form.

    • Sam Reply

      Hey there, im glad it helped. Please make sure that all your fields are getting validated. Only validated data will be returned from any form.

      • Máté Kocsis

        Ahh! Such a great idea! :D Thanks a lot! Keep up posting!

  33. bl4de Reply

    Hi Sam,

    Great work, by the way I created a little bash script for creating ZF2 module’s folders structure. Here’s link:



  34. Wesley Overdijk Reply

    “Right now this is the simplest and cleanest solution to do this – certainly not the best, but we will have to wait for the ZF/Doctrine Devs to come up with a better solution to do this.”

    May I suggest using a controller factory? In stead of using an invokable, use a factory method, and inject the form into the controller. Here, you’ll have the ServiceManager. And as long as you’re using the Doctrine module, you’ll find the EntityManager in here, too. Just inject the dependencies and it’s as clean as it’s going to get. Simply implement a getForm, and setForm in your controller and handle the rest in your factory method. (basically building the Doctrine hydrator using the entity manager).

    Just a suggestion. Registries are not cool anymore, but nice thinking :) Good article.

    • Sam Reply

      Thank you for your comment. The Problem is getting the ServiceManager down to the fieldset level. Last time i’ve checked i’ve seen an approach like you’ve just suggested. However at the time of writing this tutorial – as sadly as it sounds – but registry WAS the easiest and most productive solution – as noted though, not the best one ;)
      And that statement came from one of the main contributors of the Zend\Form Component :)

      • Wesley Overdijk

        alrighty, new idea. Populate the form with fieldsets that have pre-defined hydrators in a factory…? Just trying to not have to use the registry haha.

  35. Madhukar Reply

    Hi sam,
    Its great tutorial am really going with this. if possible can u make link for downloading source code.

    • Sam Reply

      Good suggestion, i will soon follow up with Doctrine 2 and Relationships within the next 2 weeks and then will consider putting it all onto github!

  36. Charlie Reply

    How you doing Sam!

    So I’ve been going over your tutorial, and I see that you are using zend\stdlib. what exactly is in your class Stdlib\Model\Registry and what’s it for?

    • Sam Reply

      Hi there, it’s not a Zend-Class. By the time of writing that code, there was simply no other elegant solution to get the Doctrine EntityManager down to several Fieldsets. Looking over at Github now there appears to be a way which i will cover sometime in the future, too.

      The Class itself is a simple Registry-Pattern that stores stuff at one place that i’ll be grabbing at another (i.e.: down some fieldset levels)

  37. Sam Reply

    Hello Sam!

    Great tutorial. I’m also just starting to use ZF2. I’d like to ask you: does loading a page or making an http request on you local server with ZF2 gets interrupted sometimes because it’s taking too long to load? I had tried ZF1 before I started to use ZF2 and everything was working fine then. Now, sometimes I need to hit refresh to do the same http request. Any non ZF2 page request seems to work fine. I’m using Wamp 2.2 on windows 7. If you could help me out here, I’d truly appreciate it.

    • Sam Reply

      I don’t know about WAMPP especially. Personally i haven’t had any issues at all that would have been ZF specific. Usually it’s a messed up configuration. But i’m no expert either. All my knowledge is in this blog, and i don’t have more than i wrote down :)

      • Charlie

        yeah, you got a fantastic site here!!! I was thinking of doing something similar since there wasn’t anything for true beginners like ourselves out there.

        I agree, the configuration isn’t really self explanatory. so all the loading and http requests go through with no problems, the same way as if you were requesting a simple html file?

        keep up the great work. I suppose we could probably help each other along the way.

      • Sam

        Thanks for your input! :)

  38. wd Reply

    Hi Sam, thanks for the good documented tutorial, can you update your tutorial to validate duplicate records in the database using ZF2 and Doctrine2

    • Sam Reply

      Hey there, thanks for your reply. This certainly is a valid topic you’re asking about and i will probably do a blog post about that soon ;)

  39. samsonasik Reply

    great tutorial :)

  40. cy Reply

    krass :D

Leave a Reply

Your email address will not be published. Please enter your name, email and a comment.

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code class="" title="" data-url=""> <del datetime=""> <em> <i> <q cite=""> <strike> <strong> <pre class="" title="" data-url=""> <span class="" title="" data-url="">