I forget stuff… really!!!

Zend Framework 2 + Doctrine ODM

Zend Framework 2 (ZF2) has finally reached stable… just a few weeks after starting a new project where I plan hitch the NoSQL bandwagon and tryout MongoDB… reading this particular FAQ on Zend Framework’s website..

We currently plan to fully support Zend Framework 1 until at least early 2014, including maintenance and security updates.

I guess I better start learning the latest version of this Framework… okay here goes…

1. Same as the previous version of ZF, we need to setup the VirtualHost..

<VirtualHost *:80>
	    ServerAdmin [email protected]
	    ServerName zf2odm.local

		DocumentRoot /Users/wisu/Sites/zf2odm/public
		<Directory "/Users/wisu/Sites/zf2odm/public">
			allow from all
			Options +Indexes

		SetEnv APPLICATION_ENV "development"

	    ErrorLog "logs/zf2odm-error_log"
	    CustomLog "logs/zf2odm-access_log" common

2. Get the ZF2 Skeleton

$ cd /path/to/zf2/project
$ git clone git://github.com/zendframework/ZendSkeletonApplication.git .

3. Edit the composer.json file, my setup looks like this

    "name": "zendframework/skeleton-application",
    "description": "Skeleton Application for ZF2",
    "license": "BSD-3-Clause",
    "keywords": [
    "homepage": "http://framework.zend.com/",
    "minimum-stability": "dev",
    "require": {
        "php": ">=5.3.3",
        "zendframework/zendframework": "2.0.2",
	"doctrine/doctrine-mongo-odm-module": "dev-master"

You must specify “minimum-stability” to dev, and add the “doctrine/doctrine-mongo-odm-module” repository… the default zendframework 2.* does not install… forcing version 2.0.2 seems to do the trick.. after editing, simply run

php composer.phar install

and it will install the framework along with all the dependencies required to access MongoDB..

Now we have Zend Framework 2 up and running…

4. Before continuing I think it is best to verify that we already have a MongoDB server running and make sure that PHP can talk to MongoDB… I’m not going to talk too detail about this.. googling will surely give better results…

5. Tell ZF2 that we have Doctrine and Doctrine MongoDB ODM Modules… edit config/application.config.php… my setup looks like

<?php return array( 'modules' => array( 'Application', 'DoctrineModule', 'DoctrineMongoODMModule', ), 'module_listener_options' => array( 'config_glob_paths' => array( 'config/autoload/{,*.}{global,local}.php', ), 'module_paths' => array( './module', './vendor', ), ), );<

6. Configure Doctrine ODM… copy the sample config file to the autoload directory

cp vendor/doctrine/doctrine-mongo-odm-module/config/module.doctrine-mongo-odm.local.php.dist config/autoload/module.doctrine-mongo-odm.local.php

Edit the file, my setup looks like so..

return array( 'doctrine' => array( 'connection' => array( 'odm_default' => array( 'server' => 'localhost', 'port' => '27017', 'dbname' => 'zf2odm', 'options' => array() ), ), 'configuration' => array( 'odm_default' => array( 'metadata_cache' => 'array', 'driver' => 'odm_default', 'generate_proxies' => true, 'proxy_dir' => 'data/DoctrineMongoODMModule/Proxy', 'proxy_namespace' => 'DoctrineMongoODMModule\Proxy', 'generate_hydrators' => true, 'hydrator_dir' => 'data/DoctrineMongoODMModule/Hydrator', 'hydrator_namespace' => 'DoctrineMongoODMModule\Hydrator', 'default_db' => 'zf2odm', 'filters' => array() ) ), 'driver' => array( 'odm_default' => array( 'drivers' => array( 'Application\Document' => 'aplikasi' ) ), 'aplikasi' => array( 'class' => 'Doctrine\ODM\MongoDB\Mapping\Driver\AnnotationDriver', 'cache' => 'array', 'paths' => array( 'module/Application/src/Application/Document' ) ) ), 'documentmanager' => array( 'odm_default' => array( 'connection' => 'odm_default', 'configuration' => 'odm_default', 'eventmanager' => 'odm_default' ) ), 'eventmanager' => array( 'odm_default' => array( 'subscribers' => array() ) ), ), );

7. Create Hydrator and Proxy directories

mkdir -p data/DoctrineMongoODMModule/Hydrator mkdir -p data/DoctrineMongoODMModule/Proxy

Make sure they are writable by your web server…

8. Define Document mapping… here for example is the User mapping i have… specified in module/Application/src/Application/Document/User.php

namespace Application\Document; use Doctrine\ODM\MongoDB\Mapping\Annotations as ODM; /** @ODM\Document(collection="user") */ class User { /** @ODM\Id */ private $id; /** @ODM\Field(type="string") */ private $name; /** * @return the $id */ public function getId() { return $this->id; } /** * @return the $name */ public function getName() { return $this->name; } /** * @param field_type $id */ public function setId($id) { $this->id = $id; } /** * @param field_type $name */ public function setName($name) { $this->name = $name; } }

9. To create an entry in MongoDB, we specify in our controller what mapping is to be used, here we will create a new user…

use Application\Document\User;

then sample code…

$dm = $this->getServiceLocator()->get('doctrine.documentmanager.odm_default'); $user = new User(); $user->setName("Gembul"); $dm->persist($user); $dm->flush();

in the an action to write user “Gembul” to our MongoDB’s user Collection… results is as the following…

  • Pingback: on GitHub: ZF 2 + ODM + MongoDB Simple Blog | BigWisu.com()

  • Pingback: Zend Framework 2 + Doctrine ODM | BigWisu.com - Web 2.0 BLOG | Web 2.0 BLOG()

  • MongoDB Specialist

    Excellent Tutorial!!ย 

    Just started using ZF2 and Mongo as well; you’re the only person i’ve found so far that has such a simple step by step guide. Thank You Again ๐Ÿ™‚

  • nice to know it helped someone… ๐Ÿ™‚

  • Great Tutorial thanks, had some trouble with the configuration but your tutorial solved my Problem !

  • mssb

    when I try to update composer. phar it show following error -> Your requirements could not be resolved to an installable set of packages.

    Problem 1

    – doctrine/mongodb 1.0.1 requires ext-mongo >=1.2.12, the requested PHP extension mongo is missing from your system.

    – doctrine/mongodb 1.0.0 requires ext-mongo >=1.2.12, the requested PHP extension mongo is missing from your system.

    – doctrine/mongodb-odm 1.0.0-BETA7 requires doctrine/mongodb 1.0.* -> satisfiable by doctrine/mongodb 1.0.0, doctrine/mongodb 1.0.1.

    – Installation request for doctrine/mongodb-odm 1.0.0-BETA7 -> satisfiable by doctrine/mongodb-odm 1.0.0-BETA7. please help me .

  • looks like an extension problem..

    I have mongodb extension version 1.3.1 in my PHP setup

  • Dragos

    i install all but i receive this ‘Module (DoctrineMongoODMModule) could not be initialized, everityng is fine in composer, the module was installed, do you have any idea why isn t working for me?

  • Nastron

    Thank for the tutorial! But what about getting stuff from the database?

  • Yes I plan to write about it… unfortunately been busy… ๐Ÿ™

  • ๐Ÿ™‚

  • not sure… I’ve tried a few installs on test servers running Ubuntu… don’t seem to run into such errors… :-/ .. sorry…

  • david

    Great post, thanks! One quick question, how come when I fetch the data, I got “Class User does not exist” error msg?

    $users = $dm->findBy(‘User’, array(‘name’=>”Gembul”));

  • I had the same error : doing :

    $user = $dm->getRepository(‘ApplicationDocumentUser’)->findOneBy(array(‘name’ => $name));

    worked for me.

  • Anderson Bordin

    Greate post, but why i must set both dbname and default_db? It’s really necessary?

  • I fiddled around the config, looks like we don’t need the “dbname” option..

    you are right, we don’t need both… only the default_db option

  • Anthony Marques

    I’ve tried to use but when I put “php composer.phar” the response is: Your requirements could not be resolved to an installable set of packages.

  • Pingback: Zend, MongoDB, Doctrine the perfect relationship ! | Dumi's Blog()

  • It works! Thank you!

  • MongoDB Mentalist

    I also had some trouble to find the right configuration. I always got the error message “The class ‘CourseDocumentCourse’ was not found in the chain configured namespaces ” which was not very helpful. But with your configuration i figured out what the problem was. thank you so much!

  • Davide Lookarally

    You might find this useful: http://docs.doctrine-project.org/projects/doctrine-mongodb-odm/en/latest/reference/query-builder-api.html
    and this as well http://apigen.juzna.cz/doc/doctrine/mongodb-odm/class-Doctrine.ODM.MongoDB.Query.Builder.html
    they helped me at least.
    Wisu, thanks a lot for the tutorial, it has been an absolute godsend

  • Ariden Parrochia

    me too.

    This is a Application module.config.php that will work for a hybrid solution ORM / ODM:

    ‘doctrine’ => array(
    ‘driver’ => array(
    ‘orm_driver’ => array(
    ‘class’ => ‘DoctrineORMMappingDriverAnnotationDriver’,
    ‘cache’ => ‘array’,
    ‘paths’ => array(__DIR__ . ‘/../src/’ . __NAMESPACE__ . ‘/Entity’)
    ‘orm_default’ => array(
    ‘drivers’ => array(
    __NAMESPACE__ . ‘Entity’ => ‘orm_driver’
    ‘odm_driver’ => array(
    ‘class’ => ‘DoctrineODMMongoDBMappingDriverAnnotationDriver’,
    ‘paths’ => array(__DIR__ . ‘/../src/’ . __NAMESPACE__ . ‘/Document’)
    ‘odm_default’ => array(
    ‘drivers’ => array(
    __NAMESPACE__ . ‘Document’ => ‘odm_driver’

    can help too resolve the probleme.

  • Your blog follow button doesn’t work

  • chitocruz22

    I actually made it work in a newsletter system and it works great, thank you.

  • Pingback: mongo-odm configuration (module / global) in zf2 - Tech Magazine()

  • Sandeep Dhiman

    Fatal error: Uncaught Error: Class
    ‘DoctrineODMMongoDBConfiguration’ not found in
    Stack trace:
    #0 [internal function]:
    ‘doctrine.config…’, ‘doctrine.config…’)
    call_user_func(Array, Object(ZendServiceManagerServiceManager),
    ‘doctrine.config…’, ‘doctrine.config…’)
    ‘doctrine.config…’, ‘doctrine.config…’)

    ‘doctri in /var/www/html/zend/vendor/doctrine/doctrine-mongo-odm-module/src/DoctrineMongoODMModule/Service/ConfigurationFactory.php on line 47

    Need help.

  • Diego Pereira Grassato

    I have the same problem. Any solution on this?

Powered by Wordpress | Designed by Elegant Themes