Using Doctrine 2 in Zend Framework 2

Zend Framework 2 is getting close to release, and among the changes are new ways to handle dependency injection, and new ways to work with third-party code as modules. Rob “Akrabat” Allen has updated his iconic Getting Started with Zend Framework tutorial for ZF2, and it’s a great place to start.

After working through that tutorial, the next thing I wanted to do was figure out how to get the Doctrine 2 ORM up and running.

This article shows how to set up and use Doctrine 2 in Zend Framework 2, by extending Rob’s Getting Started tutorial to use Doctrine instead of Zend_Db.

See the complete source code for this tutorial on Github.

Updated 20 September 2014: Brought up to date with current versions of the ZF tutorial and updated Doctrine composer package name.
Updated 18 June 2012: Added support for new Doctrine config file format.

Updated 2 June 2012: Added support for ZF2 beta 4 and the new composer-based installation methods.

Start with Akrabat’s tutorial

The examples here build on the sample album tracker application created in Rob Allen’s Getting Started with Zend Framework 2 tutorial. You can get the tutorial here. You can also download the code from Github. (Thanks, Akrabat!)

In the examples below, I’ll use the environment variable $PROJECT_DIR to refer to the base directory of the ZF2 tutorial. To make things easy, set that variable to the correct value for your environment. For example:

PROJECT_DIR=~/zf2-tutorial

Install Doctrine modules

Doctrine can be integrated into Zend Framework 2 as a “module” which provides all the libraries and configuration in a self-contained bundle. Installing these Doctrine modules is pretty straightforward. We’ll use Composer to install them into the project directory, and then tweak a couple configuration files.

For this example, we need the DoctrineModule, which provides common code for different Doctrine providers, and the DoctrineORMModule, a “provider” module which includes all the Doctrine2 libraries for the ORM. (For those using MongoDB, there’s also a separate ODM provider module.) See the README file for the DoctrineORMModule for further details about the installation process.

Install Doctrine with composer

Edit the $PROJECT_DIR/composer.json file, and add the following to the “require” element:

    "require": {
        ...,
        "doctrine/doctrine-orm-module": "0.*"
    },

Then run php composer.phar update to install the modules.

Configure Doctrine

Edit $PROJECT_DIR/config/application.config.php and add DoctrineModule and DoctrineORMModule to the list of modules–in that order, and before the Album module. Like this:

    'modules' => array(
        'Application',
        'DoctrineModule',
        'DoctrineORMModule',
        'Album',
    ),

Create the directory $PROJECT_DIR/data/DoctrineORMModule/Proxy and make sure the application has write access to it:

cd $PROJECT_DIR
mkdir -p data/DoctrineORMModule/Proxy
# Change www-data below to whatever group your web server runs as
sudo chgrp www-data data/DoctrineORMModule/Proxy
sudo chmod g+w data/DoctrineORMModule/Proxy

Edit the Album module config file $PROJECT_DIR/module/Album/config/module.config.php to tell Doctrine how to work with the Album namespace.

First, specify the namespace at the top of the file:

<?php
namespace Album;

This allows us to use the __NAMESPACE__ magic constant in our configuration below.

Then add this “doctrine” section to the bottom of the returned array:

return array(
    // ...
    // Doctrine config
    'doctrine' => array(
        'driver' => array(
            __NAMESPACE__ . '_driver' => array(
                'class' => 'Doctrine\ORM\Mapping\Driver\AnnotationDriver',
                'cache' => 'array',
                'paths' => array(__DIR__ . '/../src/' . __NAMESPACE__ . '/Entity')
            ),
            'orm_default' => array(
                'drivers' => array(
                    __NAMESPACE__ . '\Entity' => __NAMESPACE__ . '_driver'
                )
            )
        )
    )
);

You can see the complete module.config.php file here.

Add the database connection information in config/autoload/local.php.

return array(
    // ...
    'doctrine' => array(
        'connection' => array(
            'orm_default' => array(
                'driverClass' => 'Doctrine\DBAL\Driver\PDOMySql\Driver',
                'params' => array(
                    'host'     => 'localhost',
                    'port'     => '3306',
                    'user'     => 'YOUR_USERNAME',
                    'password' => 'YOUR_PASSWORD',
                    'dbname'   => 'zf2tutorial',
                )
            )
        )
    ),
);

Then add code to the AlbumController to get the Doctrine EntityManager from the ZF service manager. Edit $PROJECT_DIR/module/Album/src/Album/Controller/AlbumController.php and make the following changes.

Import the EntityManager namespace at the top of the file:

use Doctrine\ORM\EntityManager;

Add a protected property and a getter method:

    /**
     * @var DoctrineORMEntityManager
     */
    protected $em;

    public function getEntityManager()
    {
        if (null === $this->em) {
            $this->em = $this->getServiceLocator()->get('doctrine.entitymanager.orm_default');
        }
        return $this->em;
    }

You can now use $this->getEntityManager() within the AlbumController to access the Doctrine EntityManager.

Create the Album entity

Now that Doctrine is configured, we’re ready to replace the Zend_Db code in the tutorial with a Doctrine version.

Create a Doctrine entity for the Album in $PROJECT_DIR/module/Album/src/Album/Entity/Album.php:

<?php
 
namespace Album\Entity;
 
use Doctrine\ORM\Mapping as ORM;
use Zend\InputFilter\InputFilter;
use Zend\InputFilter\Factory as InputFactory;
use Zend\InputFilter\InputFilterAwareInterface;
use Zend\InputFilter\InputFilterInterface; 
 
/**
 * A music album.
 *
 * @ORM\Entity
 * @ORM\Table(name="album")
 * @property string $artist
 * @property string $title
 * @property int $id
 */
class Album implements InputFilterAwareInterface 
{
    protected $inputFilter;
 
    /**
     * @ORM\Id
     * @ORM\Column(type="integer");
     * @ORM\GeneratedValue(strategy="AUTO")
     */
    protected $id;
 
    /**
     * @ORM\Column(type="string")
     */
    protected $artist;
 
    /**
     * @ORM\Column(type="string")
     */
    protected $title;
 
    /**
     * Magic getter to expose protected properties.
     *
     * @param string $property
     * @return mixed
     */
    public function __get($property) 
    {
        return $this->$property;
    }
 
    /**
     * Magic setter to save protected properties.
     *
     * @param string $property
     * @param mixed $value
     */
    public function __set($property, $value) 
    {
        $this->$property = $value;
    }
 
    /**
     * Convert the object to an array.
     *
     * @return array
     */
    public function getArrayCopy() 
    {
        return get_object_vars($this);
    }
 
    /**
     * Populate from an array.
     *
     * @param array $data
     */
    public exchangeArray function ($data = array()) 
    {
        $this->id = $data['id'];
        $this->artist = $data['artist'];
        $this->title = $data['title'];
    }
 
    public function setInputFilter(InputFilterInterface $inputFilter)
    {
        throw new \Exception("Not used");
    }
 
    public function getInputFilter()
    {
        if (!$this->inputFilter) {
            $inputFilter = new InputFilter();

            $inputFilter->add(array(
                'name'     => 'id',
                'required' => true,
                'filters'  => array(
                    array('name' => 'Int'),
                ),
            ));

            $inputFilter->add(array(
                'name'     => 'artist',
                'required' => true,
                'filters'  => array(
                    array('name' => 'StripTags'),
                    array('name' => 'StringTrim'),
                ),
                'validators' => array(
                    array(
                        'name'    => 'StringLength',
                        'options' => array(
                            'encoding' => 'UTF-8',
                            'min'      => 1,
                            'max'      => 100,
                        ),
                    ),
                ),
            ));

            $inputFilter->add(array(
                'name'     => 'title',
                'required' => true,
                'filters'  => array(
                    array('name' => 'StripTags'),
                    array('name' => 'StringTrim'),
                ),
                'validators' => array(
                    array(
                        'name'    => 'StringLength',
                        'options' => array(
                            'encoding' => 'UTF-8',
                            'min'      => 1,
                            'max'      => 100,
                        ),
                    ),
                ),
            ));

            $this->inputFilter = $inputFilter;
        }

        return $this->inputFilter;
    }
}

In addition to the typical Doctrine entity stuff, the Album entity implements the InputFilterAwareInterface, along with exchangeArray() and getArrayCopy() methods. This allows it to work with the new features in ZendForm.

Update the Album controller to use Doctrine instead of Zend_Db

Finally, we’ll update each action to use Doctrine and the Album class instead of Zend_Db and the AlbumTable class. Here’s the original version of the controller from the Getting Started tutorial (as of this writing):

<?php

namespace Album\Controller;

use Zend\Mvc\Controller\AbstractActionController;
use Zend\View\Model\ViewModel;
use Album\Model\Album;
use Album\Form\AlbumForm;
use Doctrine\ORM\EntityManager;

class AlbumController extends AbstractActionController
{
    protected $albumTable;
    protected $em;

    public function getEntityManager()
    {
        if (null === $this->em) {
            $this->em = $this->getServiceLocator()->get('doctrine.entitymanager.orm_default');
        }
        return $this->em;
    }

    public function indexAction()
    {
        return new ViewModel(array(
            'albums' => $this->getAlbumTable()->fetchAll(),
        ));
    }

    public function addAction()
    {
        $form = new AlbumForm();
        $form->get('submit')->setValue('Add');

        $request = $this->getRequest();
        if ($request->isPost()) {
            $album = new Album();
            $form->setInputFilter($album->getInputFilter());
            $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);
    }

    public function editAction()
    {
        $id = (int) $this->params()->fromRoute('id', 0);
        if (!$id) {
            return $this->redirect()->toRoute('album', array(
                'action' => 'add'
            ));
        }

        // Get the Album with the specified id.  An exception is thrown
        // if it cannot be found, in which case go to the index page.
        try {
            $album = $this->getAlbumTable()->getAlbum($id);
        }
        catch (\Exception $ex) {
            return $this->redirect()->toRoute('album', array(
                'action' => 'index'
            ));
        }

        $form  = new AlbumForm();
        $form->bind($album);
        $form->get('submit')->setAttribute('value', 'Edit');

        $request = $this->getRequest();
        if ($request->isPost()) {
            $form->setInputFilter($album->getInputFilter());
            $form->setData($request->getPost());

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

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

        return array(
            'id' => $id,
            'form' => $form,
        );
    }

    public function deleteAction()
    {
        $id = (int) $this->params()->fromRoute('id', 0);
        if (!$id) {
            return $this->redirect()->toRoute('album');
        }

        $request = $this->getRequest();
        if ($request->isPost()) {
            $del = $request->getPost('del', 'No');

            if ($del == 'Yes') {
                $id = (int) $request->getPost('id');
                $this->getAlbumTable()->deleteAlbum($id);
            }

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

        return array(
            'id'    => $id,
            'album' => $this->getAlbumTable()->getAlbum($id)
        );
    }

    public function getAlbumTable()
    {
        if (!$this->albumTable) {
            $sm = $this->getServiceLocator();
            $this->albumTable = $sm->get('Album\Model\AlbumTable');
        }
        return $this->albumTable;
    }
}

And here’s my updated version using Doctrine:

<?php

namespace Album\Controller;

use Zend\Mvc\Controller\AbstractActionController;
use Zend\View\Model\ViewModel;
use Album\Entity\Album;
use Album\Form\AlbumForm;
use Doctrine\ORM\EntityManager;

class AlbumController extends AbstractActionController
{
    protected $em;

    public function getEntityManager()
    {
        if (null === $this->em) {
            $this->em = $this->getServiceLocator()->get('doctrine.entitymanager.orm_default');
        }
        return $this->em;
    }

    public function indexAction()
    {
        return new ViewModel(array(
            'albums' => $this->getEntityManager()->getRepository('Album\Entity\Album')->findAll(),
        ));
    }

    public function addAction()
    {
        $form = new AlbumForm();
        $form->get('submit')->setValue('Add');

        $request = $this->getRequest();
        if ($request->isPost()) {
            $album = new Album();
            $form->setInputFilter($album->getInputFilter());
            $form->setData($request->getPost());

            if ($form->isValid()) {
                $album->exchangeArray($form->getData());
                $this->getEntityManager()->persist($album);
                $this->getEntityManager()->flush();

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

    public function editAction()
    {
        $id = (int) $this->params()->fromRoute('id', 0);
        if (!$id) {
            return $this->redirect()->toRoute('album', array(
                'action' => 'add'
            ));
        }

        $album = $this->getEntityManager()->find('Album\Entity\Album', $id);
        if (!$album) {
            return $this->redirect()->toRoute('album', array(
                'action' => 'index'
            ));
        }

        $form  = new AlbumForm();
        $form->bind($album);
        $form->get('submit')->setAttribute('value', 'Edit');

        $request = $this->getRequest();
        if ($request->isPost()) {
            $form->setInputFilter($album->getInputFilter());
            $form->setData($request->getPost());

            if ($form->isValid()) {
                $this->getEntityManager()->flush();

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

        return array(
            'id' => $id,
            'form' => $form,
        );
    }

    public function deleteAction()
    {
        $id = (int) $this->params()->fromRoute('id', 0);
        if (!$id) {
            return $this->redirect()->toRoute('album');
        }

        $request = $this->getRequest();
        if ($request->isPost()) {
            $del = $request->getPost('del', 'No');

            if ($del == 'Yes') {
                $id = (int) $request->getPost('id');
                $album = $this->getEntityManager()->find('Album\Entity\Album', $id);
                if ($album) {
                    $this->getEntityManager()->remove($album);
                    $this->getEntityManager()->flush();
                }
            }

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

        return array(
            'id'    => $id,
            'album' => $this->getEntityManager()->find('Album\Entity\Album', $id)
        );
    }
}

That’s it!

That’s all there is to it. Thanks to Akrabat for the helpful tutorial, and to all the developers whose work makes this possible.

212 thoughts on “Using Doctrine 2 in Zend Framework 2”

    1. Thanks, Marco! I’ve been looking at your ZfDoctrineMigrations module in particular; I hope to get a chance to try that out soon.

        1. Hi Marco,

          Thanks for letting me know. I’ll add a quick note at the top for now until I get a chance to update the body of the article.

          That is just awesome that Doctrine installs with composer now. Great job on that.

    1. I do not see why not using git. I think it worth spending some time configuring it once and then it will be much easier to work with the code.

      For instance, as Zend2 is on beta, these modules are updated all the time and you’ll have to redownload those again and again. When using git you can just pull them with one command.

  1. Thank you for a very nice article.
    I have one problem though, I spent too much time trying to make it work in modular way.

    I described my module like you proposed at $PROJECT_DIR/module/Album/config/module.config.php. But when calling doctrine from command line it just says “No Metadata Classes to process”

    Paths are ok, entites are fine. When I tested them under Application/Entity with global config everything worked fine.

    Hope you can help. Thanks in advance.

    1. Hi Pavel,

      Did you create the $PROJECT_DIR/module/Application/src/Application/Entity directory? Even though there’s nothing in it, I remember getting an error from the doctrine command line tool when that directory didn’t exist.

      Jason

      1. Yes, I have a real module there, without a module it throws an exception.

        Jason, would that be hard for you to send me the entire project for this article please (maybe without any vendors)? That would be easier to spot the problem.

        Thanks

  2. First of all thanks for the great tutorial! (Also some big thanks for Akrabat!) Being kind of new to MVC a lot of questions are coming to my mind. The most prominent question is how I should expand this application.

    Let’s say I also want Artist and Genre entities; should I create new modules (/module/Artist and /module/Genre) or should I rename the Album module to MediaLibrary (or any other name of choice) and create new entities for Artist and Genre (/module/Album/src/Entity/Artist /module/Album/src/Entity/Genre)

    What’s the best practice?

  3. Thanks for this tuto, plz can you tel me where put exactly this instance array in AlbumController’s configuration

    'AlbumControllerAlbumController' => array(
    'parameters' => array(
    // 'albumTable' => 'AlbumModelAlbumTable',
    'em' => 'doctrine_em',
    ),
    ),

  4. i have this fatal error:
    Fatal error: Uncaught exception ‘ReflectionException’ with message ‘Class DoctrineORMEntityManager does not exist’ in C:wampwwwzf2-tutorialvendorZendFrameworklibraryZendCodeReflectionParameterReflection.php on line 66

    Can you help me thx

  5. Very interesting article Jason! I’m tryng to implement on my dev pc, but I have a Fatal error.. Class ‘DoctrineORMMappingDefaultNamingStrategy’ not found in .. wwwtavolevendorDoctrineORMModulevendordoctrine-ormlibDoctrineORMConfiguration.php on line 574. The akrabat tutorial works fine.. some suggestions?

    1. I don’t know if this is the right solution.. but adding namingsytrategy and defaultnamingstrategy entries to autoload_classmap solved the problem..

  6. ok, but I supposed to put

    public function setEntityManager(EntityManager $em)
    {
    $this->_em = $em;
    }

    In all my controllers?

    I must set ‘orm_driver_chain’ => array(…) in all my modules?

    In your example, you use the entity manager inside your controller.
    but, how can I use it in a service layer?

    I don’t wanna pass the EM all the times like this:

    $album = new AlbumModelAlbum($this->_em);
    $album->save($data);

    please, can you make a more advanced tutorial for doctrine2 and ZF2?

    Thank you for your amazing post!
    I was trying to learn ZF1.11 but I gave up and decide to study ZF2!
    I hope you can help me!

  7. Hello. I’ve trying to follow your tutorial, but after all changes is done I’ve get error message


    Warning: class_parents(): Class AlbumEntityAlbum does not exist and could not be loaded in /www/dev/zf2/vendor/DoctrineORMModule/vendor/doctrine-orm/lib/vendor/doctrine-common/lib/Doctrine/Common/Persistence/Mapping/RuntimeReflectionService.php on line 40

    Can you help me, what I am doing wrone?

    1. I had the same problem, it’s because you need to put “namespace Album” at the top of module.config.php inside your module :).

  8. I am learning ZF2 Doctrine 2 and have completed your tutorial and everything works fine. Thank you. Can you do a article on incorporating pagination please or maybe give me some hints how to procede. I find most of the documentation hard to follow. I am 67 and I think learning curves are getting steeper for me. Thanks, Frank

  9. Hi,
    nice tutorial! One little tweak is needed when using this with ZF2 beta3: The file “module.doctrine_orm.config.php” should be named “module.doctrine_orm.global.config.php” – otherwise, it won’t be loaded (- see config/autoload/README.md) and you will get a “No Metadata Classes to process” message from the command line tool.
    Best, Michael

  10. Hm, there seems to be more what is needed for using this configuration with ZF2 beta3. It didn’t work for me to set the EntityManager via DI (“Missing property exception”). However, I could get an Entity Manager when disablinge the DI-related Configuration in $PROJECT_DIR/module/Album/config/module.config.php (at least the orm_drivers_chain array) and use
    $em = $this->getLocator()->get(‘doctrine_em’);
    in the indexController.
    Would be nice to know how to make DI work, though. Has anyone had success with this tutorial and ZF2?

  11. It finally worked by simply disabling the orm_driver_chain config and leaving the rest of the configuration intact. My mistake: I also had disabled the DI-configuration in the same file.

  12. i am using ZF2 beta3 with DoctrineORMModule,but got the following error.

    Compile Error: ZendFrameworklibraryZendLoaderClassMapAutoloader.php line 153 – require_once() [function.require]: Failed opening required ‘vendorDoctrineORMModule/vendor/doctrine-orm/lib/vendor/doctrine-dbal/lib/vendor/doctrine-common/lib/Doctrine/Common/Annotations/AnnotationRegistry.php’ (include_path=’.;C:Program Files (x86)ZendZendServershareZendFrameworklibrary’)

  13. I follow the tutorial and use command ”
    git clone git://github.com/doctrine/DoctrineORMModule.git vendor/DoctrineORMModule –recursive ” to install DoctrineORMModule.
    but i check the folder vendorDoctrineORMModule/vendor/doctrine-orm/lib/vendor/doctrine-dbal/lib/vendor/doctrine-common,it is empty.

    do i miss any configuration?

  14. I’ve been having trouble with setting up this tutorial with ZF2 beta 4. I got the following error:

    Fatal error: Uncaught exception 'ZendDiExceptionMissingPropertyException' with message 'Missing instance/object for parameter params for DoctrineORMModuleDoctrineORMConnection::__construct' in {..} vendor/ZendFramework/library/Zend/Di/Di.php:613
    Stack trace: ...

    Maybe I dit something wrong (I’m new to ZF (2) and Doctrine :P), but it seemed the parameters for the connection were not passed trough to the connection of Doctrine.
    After I’ve changed the

    'orm_connection' => array(

    to

    'DoctrineORMModuleDoctrineORMConnection' => array(

    in the {..}vendor/DoctrineModule/config/module.config.php
    and in the {..}config/autoload/module.doctrine_orm.local.config.php it seemed to work.

  15. @Ozzi that because in the definition it requires DoctrineORMModuleDoctrineORMConnection but in DI instance it uses alias. So change the definition into its alias will solve the problem

  16. i got the next error “Fatal error: Uncaught exception ‘RuntimeException’ with message ‘Failed to load annotation mappings – check the “annotation_file” setting’ in C:xampphtdocszend2vendorDoctrineORMModuleModule.php:58 Stack trace: #0 [internal function]: DoctrineORMModuleModule->modulesLoaded(Object(ZendModuleModuleEvent)) #1 C:xampphtdocszend2vendorZendFrameworklibraryZendEventManagerEventManager.php(457): call_user_func(Array, Object(ZendModuleModuleEvent)) #2 C:xampphtdocszend2vendorZendFrameworklibraryZendEventManagerEventManager.php(199): ZendEventManagerEventManager->triggerListeners(‘loadModules.pos…’, Object(ZendModuleModuleEvent), NULL) #3 C:xampphtdocszend2vendorZendFrameworklibraryZendModuleManager.php(74): ZendEventManagerEventManager->trigger(‘loadModules.pos…’, Object(ZendModuleManager), Object(ZendModuleModuleEvent)) #4 C:xampphtdocszend2publicindex.php(14): ZendModuleManager->loadModules() #5 {main} thrown in C:xampphtdocszend2vendorDoctrineORMModuleModule.php on line 58″

    What i could do wrong?? please help me

  17. sorry i dont have the complete doctrine , but now i have this………………
    Fatal error: Uncaught exception ‘ZendDiExceptionClassNotFoundException’ with message ‘Class (specified by alias view) ZendViewPhpRenderer could not be located in provided definitions.’ in C:xampphtdocszend2vendorZendFrameworklibraryZendDiDi.php:164 Stack trace: #0 C:xampphtdocszend2vendorZendFrameworklibraryZendDiDi.php(130): ZendDiDi->newInstance(‘view’, Array) #1 C:xampphtdocszend2moduleApplicationModule.php(71): ZendDiDi->get(‘view’) #2 C:xampphtdocszend2moduleApplicationModule.php(44): ApplicationModule->getView(Object(ZendMvcApplication)) #3 [internal function]: ApplicationModule->initializeView(Object(ZendEventManagerEvent)) #4 C:xampphtdocszend2vendorZendFrameworklibraryZendEventManagerEventManager.php(457): call_user_func(Array, Object(ZendEventManagerEvent)) #5 C:xampphtdocszend2vendorZendFrameworklibraryZendEventManagerEventManager.php(199): ZendEventManagerEventManager->triggerListeners(‘bootstrap’, Object(ZendEventManagerEvent), NULL) #6 C:x in C:xampphtdocszend2vendorZendFrameworklibraryZendDiDi.php on line 164

  18. Thanks, everyone, for pointing out things that were no longer working with recent versions of ZF2.

    I’ve updated the article for ZF2 beta 3, the latest as of this writing.

    The main changes are:

    * Using the new ViewModel.

    * Changing the Doctrine config file name in the autoload directory to module.doctrine_orm.local.config.php. (It looks like this name might change again soon–a recent ZF2 planning meeting discussed dropping the “module” and “config” portions of these config file names.)

    Please let me know if you find anything that still isn’t working right.

    Thanks!

  19. Hey,
    Great tutorial, it helped me to setup zf2 and doctrine quickly! Thank you! I would like also to suggest you, if possible, write how to unit test it.

  20. Hello there!
    I just wanted to invite anyone having issue with this procedure (also asking the author of the article if he can update it) to post any issue at https://github.com/doctrine/DoctrineORMModule/issues .
    I’ve been working a bit on the module and the changes could not reflect what described in this article, so please eventually help me by keeping the DoctrineModule and DoctrineORMModule docs updated.

    Thank you!

    1. That is because submodules are not available at all anymore! I’ve dropped them because a single clone --recursive would cause something like 350Mb of disk space to be gone :P

      1. @Marco Piveta: I am new in ZF2 and I has been working with Zend Skeleton Application and i want integrate Doctrine 2 with ZF2 but I can not connect to the github because the network where I’m working is restricted .
        I wondering if you can provide me the full application with doctrine 2(Zend Skeleton Application+ Doctrine 2 +DoctrineModule +DoctrineORMModule) in case that be possible, please send me a link to download this or send to my e-mail.
        Greetings
        I hope your answer.

    2. Thanks for the comment, Rod. I added a quick note to the article to use Composer instead of Git submodules, until I get time to bring the article up to date.

    1. Indeed this tutorial need some updates.
      Rob Allen updated his tutorial for the new beta 4 what has some major changes.
      This tutorial doesnt work if u apply it over the tutorial from Rob.

      Besides that i appriciate the work and it is still a good tutorial. Keep up the good work!

      1. I finally updated the tutorial with support for ZF2 beta 4 and the new composer-based module installation. Please let me know if you find anything that still doesn’t work right.

        Thanks for the feedback!

  21. Good tutorial, it run perfectly for me.
    So.. I have a question, how can I handle EntityManager in an intermediate class between Entities and Controllers. I explain…
    e.g. If I want to do own queries with dql or sql, where exactly I should place, I’m thinking to doing in a class wich is instanciated by Controller and use entitymanager.

      1. Thanks, just I wanted, it works already- Only a question, in my dql : ‘SELECT u FROM MyDomainModelUser u WHERE u.status = “admin”‘ is not possible use User only.
        I’m trying but I have error wich doesn’t recognize Class User.
        Thanks again…!

        1. Hi Wil,

          Unfortunately, I don’t think it’s possible to use “SELECT u FROM User” instead of “SELECT u FROM MyDomainModelUser”. At least, not according to the DQL SELECT clause documentation, which says “The FROM keyword is always followed by a fully-qualified class name”.

          Since the DQL query is just a string, I don’t see how Doctrine could automatically resolve the namespace from the calling code.

          Jaosn

  22. Hello, thanks for the tutorial.
    I followed the steps and I get this error

    RuntimeException’ with message ‘Module (DoctrineModule) could not be initialized.’

    Could you help?

      1. Hi Kieran and Alex,

        One possible cause of that error is that the doctrine vendor library doesn’t exist. Do you have a vendor/doctrine/DoctrineModule directory?

        Try making sure you have "doctrine/DoctrineORMModule": "dev-master" in the require block of your composer.json, and then run php composer.phar update to download any missing vendor libraries.

        If it helps, here’s my working version of the tutorial on Github: https://github.com/jasongrimes/zf2tutorial

        Please let me know how it goes.

        Thanks,

        Jason

        1. Hi Jason,

          I have downloaded those files , seems not to recognize the path ‘vendor’

          require_once (getenv(‘ZF2_PATH’) ?: ‘/vendor/doctrine’);

          failed to open stream: Permission denied

          1. Please ignore previous, is no the path vendor

            require_once (getenv(‘ZF2_PATH’) ?: ‘/vendor/autoload.php’);

            returns a 404

        2. Hello Jason, Alex and Kieran,
          I had a similar problem when running php composer.phar update, the error message was “The requested package doctrine/doctrineormmodule dev-master could not be found”
          I followed the reference to a discussion about composer-dev and managed to get a nice download en installation of doctrine with the following lines in the composer.json file:
          {

          “homepage”: “http://framework.zend.com”,
          “minimum-stability”: “dev”,
          “require”: {
          “php”: “>=5.3.3″,
          “zendframework/zendframework”: “dev-master#dtb .. etc,
          “doctrine/doctrine-orm-module”: “dev-master”
          }
          }

          The line about “minimum-stability” appears to me to be the important change from what is in Jason’s tutorial.
          I wrote this while composer was installing, so I hope that I can continue now with following your tutorial. Hope this helps for some others.

          Martin de Groot

  23. Just wanted to let you know that this blog post needs updated as I’ve updated the DoctrineModule and DoctrineORMModule to ZF2 beta4. Few minor tweaks (connection/driver) and you should be good to go. Nice post.

  24. There’s a problem when a field don’t pass the validation, the select fields don’t set the submitted value (they don’t set nothing at all).
    I found that this occurs because the types don’t match. In this case, the value from the form is a string (because everything coming from a form is a string) and the options are integer, so in the in_array with strict on is never true.
    I don’t know how to solve this… could anyone help me please?

      1. Hi Alex,

        Glad you sorted it out. I noticed that the DoctrineORMModule README file says the service is registered as doctrine.entitymanager.orm_default instead of DoctrineORMEntityManager, so I made that change in the tutorial code as well. Both ways seem to work for me right now, though.

  25. “doctrine/DoctrineORMModule”: “dev-master” within the require block and an “php composer.phar update” results in “Your requirements could not be solved to an installable set of packages.”[...]“doctrine/doctrinemodule dev-master -> no matching package found”

    I get this in both working environments (home and work) – any ideas?

    1. Using “doctrine/doctrine-orm-module”: “dev-master” as hinted at the README file from Doctrines github results in not found packages, too :S

    2. OK, the reason it didn’t work is because the files are not STABLE. You need to add “minimum-stability”: “dev”, to the root of your composer.json and then it works. Be sure to remove this line though, ones the modules go stable

  26. While our competitors use useless techniques in stopping digital piracy,
    we use our insights about the guerrilla file-sharing scene.
    Whereas you can find a good number of the data via simple and
    easy search parameters, those files are already downloaded thousands maybe even more times.

    We guarantee that we eliminate the Source movies that come from non-indexed blogs or membership
    web sites. That will restrict any serious distribution to file-sharing or streaming websites that are popular to
    the majority of the internet.

  27. Anyone have any luck with zf2 Beta 5. The album list displays find, but edit and delete doesn’t work.

    Just curious if anyone else has had any luck.

    Thanks,

    Greg

  28. there are a few differences for beta5:

    • the composer.json config differs (look at doctrine-readme) [1]
    populate() is now exchangeArray()
    ZendMvcControllerActionController is now ZendMvcControllerAbstractActionController
    $this->getEvent()->getRouteMatch()->getParam(‘id’) is now $this->params(‘id’)
    • I don’t have $form->setBindOnValidate(false) or $form->bindValues()
    • at the deleteAction I had to remove ->getArrayCopy to work.
    • There are two different Versions of getEntityManager() in the article above. The Version with DoctrineORMEntityManager works for me, so I didn’t add the above one.

    To get it work, I also had to do the changes described in doctrine issue #79 [2]

    I’m not really sure that that was everything. Can anyone please confirm, so Jason can adjust the article.

    1: https://github.com/doctrine/DoctrineORMModule/blob/master/README.md
    2: https://github.com/doctrine/DoctrineORMModule/issues/79

      1. do u have the solution for this issue

        Warning: class_parents(): Class UserEntityUser does not exist and could not be loaded in D:xampphtdocsSitezarvendordoctrinecommonlibDoctrineCommonPersistenceMappingRuntimeReflectionService.php on line 40

  29. Items I’ve tweaked with success in ZF2 Beta 5 and latest doctrine release so far.

    1 – To allow index action to load – Changed AlbumController to extend AbstractActionController i.e. change:

    use ZendMvcControllerActionController;
    //….
    //….
    class AlbumController extends ActionController

    to

    use ZendMvcControllerAbstractActionController;
    //….
    //….
    class AlbumController extends AbstractActionController

    2 – To allow index action to load file was requesting ZendStorageCacheFactory from DoctrineModule/Service dir. The Class couldn’t be found, looks like the class in the directory was ZendCacheStorageFactory so duplicated class and created a ZendStorageCacheFactory class, changed name of class to match as well (Note this wasn’t happening at first, showed up after I reloaded files using composer, might have accidentally pulled in a different build of composer)

    3 – To allow the delete action to load – in AlbumController.php in public function deleteAction, at bottom in the return array( ) I commented out the ->get array copy() from the line:

    ‘album’ => $this->getEntityManager()->find(‘AlbumEntityAlbum’, $id) //->getArrayCopy()

    4 – Fix delete action – change the post() function to getPost() in the deleteAction() function. I.e. change from:

    $del = $request->Post()->get(‘del’, ‘No’);
    if ($del == ‘Yes’) {
    $id = (int)$request->Post()->get(‘id’);

    to

    $del = $request->getPost()->get(‘del’, ‘No’);
    if ($del == ‘Yes’) {
    $id = (int)$request->getPost()->get(‘id’);

    5 – Change delete action redirect to:

    // Redirect to list of albums
    return $this->redirect()->toRoute(‘album’);

    6 – To fix edit action change the the public function editAction() of the AlbumController change the post() to getPost():

    $form->setData($request->post());

    to

    $form->setData($request->getPost());

    6 – To fix the addAction() function in the AlbumController change the post() to getPost() i.e. change

    $form->setData($request->post());

    to

    $form->setData($request->getPost());

    Seems to have it up and working for me – thanks everyone who put in all the hard work on coding these items, and providing the tutorials. Been a real help for me so far. Been fun for me to dive into something new, really like ZF2 and the doctrine module so far.

  30. Ah, as Blaimi posted looks like they already fixed the ZendStorageCache error for doctrine. So you can probably ignore that part of my fix above.

    Notes from Git
    got an error after install. “Class ZendStorageCacheFactory” not found …

    Issue resolved

  31. ATTENTION (to user with ZF beta5)

    With the ZF2 beta5, in the AlbumController, you have to use the AbstractActionController instead of the ActionController

    And request->getPost() instead of request->post()

  32. while installing doctrine with composer shouldn’t it be “doctrine/Doctrine-ORM-Module”: “dev-master” instead of “doctrine/DoctrineORMModule”: “dev-master”?

  33. hi everyone,
    nice tutorial, but I’m confronted with this error

    Class AlbumEntityAlbum is not a valid entity or mapped super class.

    I use Zf2 Beta5,

    Somebody can help me?

    Thanks

  34. hi everyone,
    nice tutorial, but I’m confronted with this error

    Class AlbumEntityAlbum is not a valid entity or mapped super class.

    I use Zf2 Beta5,

    Somebody can help me?

    Thanks

  35. Hey @all,
    i’ve the same problem with the latest version installed by composer. after copy the (before) working album module to /modules/ , i get the
    “Class AlbumEntityAlbum is not a valid entity or mapped super class” message. is there anything we must change in the current album code to make the code running? Or is there a probleme in DoctrineORM latest code ??
    Thanks a lot

  36. Hi all,
    as Dah and mludewig, I am also encountering the same problem with error message:
    Class AlbumEntityAlbum does not exist

    Any updates on this issue. I am also using ZF2 Beta 5.

    Thanks

  37. Hallo webdefy!

    I had the problem too but I do not know how I fixed it. :(
    I think orm was not installed.

    my require in composer.json for zf2 2.0.0 rc1

    “require”: {
    “php”: “>=5.3.3″,
    “zendframework/zendframework”: “dev-master”
    ,”zendframework/zend-developer-tools”: “dev-master”
    ,”doctrine/doctrine-orm-module”: “dev-master”
    ,”doctrine/migrations”: “dev-master”
    ,”doctrine/dbal”: “2.2.2”
    ,”doctrine/common”: “2.2.2”
    ,”doctrine/doctrine-module”: “dev-master”
    ,”doctrine/data-fixtures”: “dev-master”
    }

  38. Hallo Klea,
    thanks for replying to my post, I followed you suggestion, but alas with no better results. Any other suggestion

    Thanks

  39. @Klea, I have now exactly the same error:
    Class AlbumEntityAlbum is not a valid entity or mapped super class.. Well has somebody an idea how to resolve this.

    Thanks

  40. Thank you for this tutorial. I have always thought one argument for using doctrine was that it reduces the code to be written for db interactions.
    Comparing the original Album Controller with yours reveals the opposite.

  41. I get this Error:
    PHP Fatal error: Class ‘Doctrine\Common\Annotations\AnnotationRegistry’ not found in /usr/local/zend/apache2/htdocs/zf2-tutorial/vendor/DoctrineORMModule/src/DoctrineORMModule/Module.php on line 65

    DoctrineModule and DoctrineORMModule are both installed to vendor directory.

  42. Hi snorri!

    Unfortunately I have no time to concern myself with this issue. :( The /vendor/doctrine/common directory doesn’t exist. Right? To fix you have to edit your composer.json to load “doctrine/common” and run composer.phar update i think.

  43. Hi

    I have an issue , i need help in creating the forms. Assume the there are group of fields and added to fieldset and multiple fieldsets are added using collections but i am unable to validate the form

    Thank u,
    with Regards,

  44. i have en error when i want to use doctrine command do generate entities:

    Fatal error: Class ‘Zend_Config_Ini’ not found in D:diplomaoglasnikdbcli-con
    fig.php on line 29

    29 line is cli-config.php is:

    $config = new Zend_Config_Ini( APPLICATION_PATH . ‘/../application/configs/application.ini’,’development’);

    I realy need some help, because i am new with doctrine :)
    Tnx

  45. The composer require String changed from
    “doctrine/doctrineORMModule”: “dev-master”
    to
    “doctrine/doctrine-orm-module”: “dev-master”

  46. This is a great article however I am having difficulty on the last step, getting the entity loaded, I keep getting this error:

    Class AlbumEntityAlbum is not a valid entity or mapped super class.

    Any ideas how to fix this? Seems like alot of people are getting this same error

  47. I’ve done everything with default skeleton application and the transfered changes from Akrabat’s and it worked, but after adding line to composer.json as described here I’m getting


    Loading composer repositories with package information
    Updating dependencies
    Segmentation fault

  48. Hi all,
    had any one worked on the validation part using Doctrine 2 and Zend Framework 2, I am looking for an example for validate fields, for example in this Album module validate the Album name for duplicate records in the database. In case any one worked on this, can share some knowledge here. Thanks

  49. Hello everyone,
    thanks to the author for this tutorial.
    I have a question, it is possible to autogenerate the entity class?

    I have db tables with more than hundred columns, it would be a long and repetitive work to create entity classes by hand.

    Thanks

  50. the following lines should be pasted inside PROJECT_DIRconfigautoloadlocal.php [not in local.php.dist]:

    return array(
    // …
    ‘doctrine’ => array(
    ‘connection’ => array(
    ‘orm_default’ => array(
    ‘driverClass’ => ‘DoctrineDBALDriverPDOMySqlDriver’,
    ‘params’ => array(
    ‘host’ => ‘localhost’,
    ‘port’ => ‘3306’,
    ‘user’ => ”,
    ‘password’ => ”,
    ‘dbname’ => ‘zf2tutorial’,
    )
    )
    )
    ),
    );

    . .it solved my problem, thanks for this wonderful tutorial :)

      1. wow Eric. i’m glad i was able to help. that problem really freaked me out. took me 2weeks to find out that little problem.

  51. Thanks for nice and useful intro to Doctrine.

    In my case I change in ActionControler deleteAction
    from:

    return array(
    'id' => $id,
    'album' => $this->getEntityManager()->find('AlbumEntityAlbum', $id)->getArrayCopy()
    );

    to:

    return array(
    'id' => $id,
    'album' => $this->getEntityManager()->find('AlbumEntityAlbum', $id)
    //remove ->getArrayCopy() for object like access in phtml to album var
    );

    without this example not work Notice: Trying to get property of non-object in …/delete.phtml [$album->title]

    Thanks and sorry for my English is not my native

  52. Hi,

    First of all thanks for this great tutorial.

    I got this error when I submitted data from the “add” action.

    Call to undefined method ZendHttpPhpEnvironmentRequest::post() in C:xampphtdocszendskeletonmoduleAlbumsrcAlbumControllerAlbumController.php on line …

    Changing this line in the addAction

    $form->setData($request->post());

    to this line


    $form->setData($request->getPost());

    fixed it.

    Is this the right way to do it ?

  53. Hey Jason,

    i think composer doesn’t accept names with capital letters in any longer, so:

    “require”: {
    …,
    “doctrine/DoctrineORMModule”: “dev-master”
    }

    must be repleaced with:

    “require”: {
    …,
    “doctrine/doctrine-orm-module”: “dev-master”
    }

  54. Hi thanks for this tutorial. There is an issue with this composer configuration:

    "doctrine/DoctrineORMModule": "dev-master"

    issue:

    – The requested package doctrine/doctrineormmodule dev-master could not be found.

    regards

  55. An error occurred
    An error occurred during execution; please try again later.
    Additional information:
    DoctrineCommonPersistenceMappingMappingException

    File:

    C:rootzf2-tutorialvendordoctrinecommonlibDoctrineCommonPersistenceMappingMappingException.php:38

    Message:

    The class ‘AlbumEntityAlbum’ was not found in the chain configured namespaces

    I need help
    thanks

    1. I know this is an old post, but i ran into this problem and had to look the answer on google. The problem is that inside module.config.php you need to add namespace Album; in beginning of the file.

      Because module.config.php has constants that uses, namely __NAMESPACE__ constant. And if module.config.php is not configured within a namespace it will look for the mapping class inside Entity and not inside AlbumEntity namespace.

      I think that is the cause and solution. Sorry a bit late, but i only started with Zend few days ago.

  56. Do you know anything about the CLI-tools?
    If i try to run, for example, “./doctrine-module orm:schema-tool:update” I get an exception that the driver is not found. It seems like some more autoloading is required…

  57. I followed your nice tutorial but when updating Schema i get this error:
    [InvalidArgumentException]
    The helper “em” is not defined.

  58. i tried with your example and receive this :

    – The requested package doctrine/doctrineormmodule could not be found in any version, there may be a typo in the package name.

    if i install like doctrine documentaion say icannot put this:

    ‘DoctrineModule’,
    ‘DoctrineORMModule’ receive errors.

  59. Hi Jason, thank you for this! It works like an absolute charm!! I’ve never worked with an ORM, so I am looking forward to the new experience.

    I have one more favor to ask please:
    would you be so kind as to change your tutorial to reflect the fixes made by @shanethehat please?
    Setting up Doctrine with Zend Framework 2

    I would like to include the URL to this tutorial in the comments section of my Doctrine controller file and referencing 2 tutorials seems a bit messy.

    I will credit you as the author and shane as a contributor if that’s ok.

    Once again, thank you!

  60. oke, i am not usually the sort of guy that posts and reacts on blogs. but i encounterd an error(and the fix for it) that is worth sharing with you all.

    if you have a typo in your class name that mismatches with the entity file name. you get a fatal error saying the class has already been declared.

    this message gives you false input and can give you many headaches!

  61. Hi,

    Great Tutorial!

    I have one question, which you may or may not have an answer to, and it might be a stupid one.

    Given that ZF2 is modular, is there a way of using Doctrine’s CLI tool to generate the entities to their current location?
    When you run the CLI tool, you have to specify a destination path, but obviously this wont work as all entities from all modules will be dumped in the one directory which will cause issues when trying to access them.

    Any suggestions would be great!

    Cheers

  62. followed everything described in this tutorial and i get this PHP Fatal error: Uncaught exception ‘ZendLoaderExceptionInvalidArgumentException’ with message ‘Autoloader class “doctrine” not loaded’ in S:zendserverApache2htdocspgep-moteur-synchrovendorzendframeworkzendframeworklibraryZendLoaderAutoloaderFactory.php:92

  63. In case that anyone is having problem with running the unit testing from the original example you need to include the DoctrineModule’ and ‘DoctrineORMModule’ to your modules array in your TestConfig.php file or you will get a constant error when running phpunit: ZendServiceManagerExceptionServiceNotFoundException: ZendServiceManagerServiceManager::get was unable to fetch or create an instance for doctrine.entitymanager.orm_default

  64. i came with issue googled but no use please help me

    Warning: class_parents(): Class UserEntityUser does not exist and could not be loaded in D:xampphtdocsSitezarvendordoctrinecommonlibDoctrineCommonPersistenceMappingRuntimeReflectionService.php on line 40

  65. Hi.

    I’m getting an Error 500.

    This is what my log shows:

    [Thu Dec 27 02:23:43 2012] [error] [client 127.0.0.1] PHP Fatal error: Uncaught exception ‘Zend\ServiceManager\Exception\ServiceNotFoundException’ with message ‘Zend\ServiceManager\ServiceManager::get was unable to fetch or create an instance for translator’ in /Library/WebServer/Documents/zf2-tutorial/vendor/zendframework/zendframework/library/Zend/ServiceManager/ServiceManager.php:452nStack trace:n#0 /Library/WebServer/Documents/zf2-tutorial/module/Application/Module.php(19): Zend\ServiceManager\ServiceManager->get(‘translator’)n#1 [internal function]: Application\Module->onBootstrap(Object(Zend\Mvc\MvcEvent))n#2 /Library/WebServer/Documents/zf2-tutorial/vendor/zendframework/zendframework/library/Zend/EventManager/EventManager.php(464): call_user_func(Array, Object(Zend\Mvc\MvcEvent))n#3 /Library/WebServer/Documents/zf2-tutorial/vendor/zendframework/zendframework/library/Zend/EventManager/EventManager.php(208): Zend\EventManager\EventManager->triggerListeners(‘bootstrap’, Object(Zend\Mvc\MvcEvent), Array)n#4 /Library/WebServer/Documents/zf2-tutorial/vendor/zendframework/zendfr in /Library/WebServer/Documents/zf2-tutorial/vendor/zendframework/zendframework/library/Zend/ServiceManager/ServiceManager.php on line 452

  66. Hi when I use php composer.phar after added one line “doctrine/DoctrineORMModule”: “dev-master” in composer.json that time i getting following issue so help me

    D:ZendSkeletonApplication>php composer.phar update
    Loading composer repositories with package information
    Updating dependencies
    Your requirements could not be resolved to an installable set of packages.

    Problem 1
    – The requested package doctrine/doctrineormmodule could not be found in any
    version, there may be a typo in the package name.

    Potential causes:
    – A typo in the package name
    – The package is not available in a stable-enough version according to your min
    imum-stability setting
    see f
    or more details.

    Read for further common
    problems.

  67. Hi Guys,

    Thanks for such a great tutorial. It was a life saver for me. I have one question regarding the doctrine entity models. Instead of storing the model files into each module’s Entity folder, is it possible to store all entity model files into a single location. what do we need to change in our module.config.php to make this happen.

    Your help will be greatly appreciated mate. Cheers.

  68. Hi Jason, this is my question how do i use doctrine2 with zf2 with multiple database connections? i already tried adding entries to the connection section y config/autoload/global.php the true problem seems how do i tell to the entity manager wich connection use at anytime.
    i really apreciate a swift response. Thnx ^_^

  69. __get() property body should be exactly as follows:

    public function __get($property) {
    if(property_exists($this, $property)) {
    return $this->$property;
    }
    }

  70. An excellent tutorial! Got my code switched over almost straight away

    I had an issue installing initially via Composer, and had to change the composer.json to the following:

    “doctrine/orm”: “*”,
    “doctrine/doctrine-orm-module”: “*”

    Using the package listed at the top, or trying to change these to dev-master, results in “Your requirements could not be resolved to an installable set of packages.”

  71. Hi,

    I seriously need help. Just need addaction code for zend 2.1.4 dev.

    I have corrected the code for delete but i cant correct for addAction

    Fatal error: Call to undefined method AlbumModelAlbum::populate() in moduleAlbumsrcAlbumControllerAlbumController.php

    I know i need object of album entity and i am not getting it to use populate method.

    Please help i am in urgent need

    Thanks!!

    1. A 404 error occurred
      Page not found.
      The requested controller could not be mapped to an existing controller class.

      Controller:
      album/album(resolves to invalid controller class or alias: album/album)
      No Exception available

      Can somebody provide an solution? Zfcuser is working with doctrine

      Thanks

  72. I think
    “require”: {
    …,
    “doctrine/DoctrineORMModule”: “dev-master”
    },

    is wrong it should be
    “require”: {
    …,
    “doctrine/doctrine-orm-module”: “dev-master”
    },

  73. I am getting this message.

    Deprecated: Polyfill autoload support (file library/Zend/Stdlib/compatibility/autoload.php) is no longer necessary; please remove your require statement referencing this file in /var/www/rahul/learning/zend4/ZendSkeletonApplication/vendor/zendframework/zendframework/library/Zend/Stdlib/compatibility/autoload.php on line 14

  74. I quite appreciate your work. Straight and Simple.
    Is it possible to work with Doctrine CLI from the bin directory???
    I tried it but I got some errors.
    Perhaps there’s something very simple I could do to correct it.
    It just says something like:
    [InvalidArgumentException]
    The helper “em” is not defined.

    I don’t want to mess with the configuration till I’m sure I know what I’m doing. It is an important project.

    Thanks in advance for any help.

  75. The composer.json file have to be updated.

    Instead of

    "doctrine/DoctrineORMModule": "dev-master"

    We should get


    "doctrine/doctrine-module": "dev-master@dev",
    "doctrine/doctrine-orm-module": "dev-master@dev"

    Thank you for the toturial.

  76. Thx alot for you’ tutorial it’s very helpful , all work fine for me just the Delet Acion when i try to delete some recored i have this Error “Trying to get property of non-object in /home/../Album/view/album/album/delete.phtml on line 14 Call Stack”

    url('album', array('action' => 'delete', 'id'=>$this->id)); ?>
    <form action="" method="post">

    <input type="hidden" name="id" value="id; ?>" />

    i think the probleme is on “$album->id”
    i used the Akrabat Projet like you mention .
    Any help please .

  77. I have used __get and __set magic methods in my entity. But for some attributes i want to manually override getter function. for example if i have attribute user, i want it to call getUser instead of __get accesses with $obj->user

    how this can be achieved

  78. Warning: class_parents(): Class AlbumEntityAlbum does not exist and could not be loaded in /var/www/zf2-tutorial/vendor/doctrine/common/lib/Doctrine/Common/Persistence/Mapping/RuntimeReflectionService.php on line 40

    Warning: array_reverse() expects parameter 1 to be array, boolean given in /var/www/zf2-tutorial/vendor/doctrine/common/lib/Doctrine/Common/Persistence/Mapping/AbstractClassMetadataFactory.php on line 257

    Warning: Invalid argument supplied for foreach() in /var/www/zf2-tutorial/vendor/doctrine/common/lib/Doctrine/Common/Persistence/Mapping/AbstractClassMetadataFactory.php on line 257

    Fatal error: Uncaught exception ‘DoctrineCommonPersistenceMappingMappingException’ with message ‘File mapping drivers must have a valid directory path, however the given path [/var/www/zf2-tutorial/module/Album/config/../src/Album/Entity] seems to be incorrect!’ in /var/www/zf2-tutorial/vendor/doctrine/common/lib/Doctrine/Common/Persistence/Mapping/MappingException.php:61 Stack trace: #0 /var/www/zf2-tutorial/vendor/doctrine/common/lib/Doctrine/Common/Persistence/Mapping/Driver/AnnotationDriver.php(179): DoctrineCommonPersistenceMappingMappingException::fileMappingDriversRequireConfiguredDirectoryPath(‘/var/www/zf2-tu…’) #1 /var/www/zf2-tutorial/vendor/doctrine/common/lib/Doctrine/Common/Persistence/Mapping/Driver/MappingDriverChain.php(132): DoctrineCommonPersistenceMappingDriverAnnotationDriver->getAllClassNames() #2 /var/www/zf2-tutorial/vendor/doctrine/common/lib/Doctrine/Common/Persistence/Mapping/AbstractClassMetadataFactory.php(111):
    DoctrineCommonPersistenceMappingDriverMappingDriverChain->getA in /var/www/zf2-tutorial/vendor/doctrine/common/lib/Doctrine/Common/Persistence/Mapping/MappingException.php on line 61

  79. Nice Turtorial! One question….I have other database names like objId, objArtist and objTitle but I want to have your object names in Entity/Album lile id, artist, title….
    and I don’t know how….
    when I have same column titles and entity object names it works fine, but how can I have different names?

    1. I found the solution…
      /**
      *
      * @var string @ORMColumn(name=”objArtist”, type=”string”, length=255,
      * nullable=true)
      */
      protected $artist;

  80. I have another question. I want to use two modules with Doctrine ORM. The Album module alone works perfectly. But when I have another moduless I got an error:
    “The class ‘VacationEntityVacation’ was not found in the chain configured namespaces”

    Why? in both module.config.php I have a namespace set and the ‘doctrine’ configuration…whats the problem?

    1. That’s interesting. I’m trying to put some entities directly in the Application module for testing and I’m encountering the same error, even though I have the namespace set in Application/config/module.config.php – I’m going to try moving it to its own module to see if that helps.

  81. I tried caching the Doctrine entity object using zend cache service. It works fine if the entity object does not have any foreign key reference but fails when the entity object has a foreign key reference and points to an entity belonging to different namespace.

    It was throwing this error – The script tried to execute a method or access a property of an incomplete object. Please ensure that the class definition DoctrineORMModuleProxy__CG__AttachmentEntityAttachment of the object you are trying to operate on was loaded before unserialize() gets called or provide a __autoload() function to load the class definition in /home/vaishnavi/NetBeansProjects/testsuite/module/Test/view/test/test/view-test-case.phtml

    Fixed the above error by autoloading the proxy classes in init_autoloader.php by providing this –

    use DoctrineORMProxyAutoloader;

    $proxyDir = __DIR__.”/data/DoctrineORMModule/Proxy”;
    $proxyNamespace = “DoctrineORMModuleProxy”;
    Autoloader::register($proxyDir, $proxyNamespace);

    Now the above error does not come but does not display the property values of foreign key reference class. Can somebody help?

  82. Hi,

    Firstly congrats for this article!
    Helped me very much.

    Secondly the package “doctrine/DoctrineORMModule” has been replaced by “doctrine/doctrine-orm-module”. It would be nice to update the text.

    Thanks.

  83. Hello, i Have found a problem in your code: the method $form->setData($request->post()); (at the line 48,77and 104) was not working, and i replace it by getPost() and it’s working.

  84. Hello,

    thank you for your tutorial.

    I receive an error “Undefined namespace ORM. Referenced namespace not found.” at the following section:

    class AlbumController extends ActionController
    {
    /**
    * @var DoctrineORMEntityManager
    */
    protected $em;

    Can somebody help me, please?

  85. After following the instruction above i got this..

    The class ‘AlbumEntityAlbum’ was not found in the chain configured namespaces

    if i remove the Album.php in entity folder
    i got this
    Class ‘AlbumEntityAlbum’ does not exist

    can anyone help me out pls :(

  86. opss.. i got it fixed… xD i changed the
    use AlbumModelAlbum
    to
    use AlbumEntityAlbum

    so sorry just a newbie… I didn’t notice your changes on the use… >_<

  87. sir, my error is
    Warning: DoctrineModuleModule::init(): It is not safe to rely on the system’s timezone settings. You are *required* to use the date.timezone setting or the date_default_timezone_set() function. In case you used any of those methods and you are still getting this warning, you most likely misspelled the timezone identifier. We selected the timezone ‘UTC’ for now, but please set date.timezone to select your timezone. in D:Program FilesZendZendServerdataappshttp__default__zfAlbumDoc1.0.0moduleDoctrineModulesrcDoctrineModuleModule.php on line 55

    Fatal error: Class ‘DoctrineCommonAnnotationsAnnotationRegistry’ not found in D:Program FilesZendZendServerdataappshttp__default__zfAlbumDoc1.0.0moduleDoctrineModulesrcDoctrineModuleModule.php on line 55

  88. We can’t reach Album’s property in the IDE after (->) when get the object with getRepository.() How can we use objects’s properties with IDE? (autocomplete)

  89. About – “doctrine/doctrine-orm-module” at composer.json

    It is working to me, after I added the following line.

    “minimum-stability”: “dev”,

    Here is my final code for my composer.json

    {
    “name”: “zendframework/skeleton-application”,
    “description”: “Skeleton Application for ZF2″,
    “license”: “BSD-3-Clause”,
    “keywords”: [
    "framework",
    "zf2"
    ],
    “homepage”: “http://framework.zend.com/”,
    “minimum-stability”: “dev”,
    “require”: {
    “php”: “>=5.3.3″,
    “zendframework/zendframework”: “2.3.*”,
    “doctrine/doctrine-orm-module”: “dev-master”
    }
    }

  90. I am using DAO design patterns. So I don’t like to get Entity Manager from controller like this. Because here you have the entity manager within the controller you introduce a coupling of your “domain logic”

    public function getEntityManager()
    {
    if (null === $this->em) {
    $this->em = $this->getServiceLocator()->get(‘DoctrineORMEntityManager’);
    }
    return $this->em;
    }

    Better if I can take it from DAO or from a factory class. How I can do that ?

  91. All good but why getInputFilter() has to be in entity doctrine entity class ? shouldn’t it be in the form class as its more relevant ?

    Thanks
    Sergiu

  92. you have an example with two or more tables used with Doctrine 2 with Zend Framework 2? Im finding difficulties in retrieving, updating and deleting data on those table. Any help would be appreciated. Thanks.

Leave a Reply

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

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