Quantcast
Viewing latest article 5
Browse Latest Browse All 12

Using Doctrine 2 in Zend Framework 2

Image may be NSFW.
Clik here to view.

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.

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/DoctrineORMModule": "dev-master"
    },

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',
    ),

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'     => '',
                    '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:

use Zend\Mvc\Controller\ActionController,
    Zend\View\Model\ViewModel,
    Album\Model\AlbumTable,
    Album\Model\Album,
    Album\Form\AlbumForm,
    Doctrine\ORM\EntityManager;     // Add this line

Add a protected property and a getter method:

 
    /**             
     * @var Doctrine\ORM\EntityManager
     */                 
    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:

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

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):

And here’s my updated version using Doctrine:

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.


Viewing latest article 5
Browse Latest Browse All 12

Trending Articles