2 – Setup Doctrine 2 in ZF2

Setting up our blog application we now will be configuring both Zend and Doctrine. By default nothing is configured in the Zend Skeleton Application.

The configuration files for your application are located in the /config folder. For now, modify the /config/autoload/global.php and create a /config/autoload/local.php.

Modify the global.php to contain the following configuration:

return [
    'db' => [
        'driver' => 'Pdo',
        'dsn'    => 'mysql:dbname=blog;host=localhost',
        'driver_options' => [
            PDO::MYSQL_ATTR_INIT_COMMAND => 'SET NAMES \'UTF8\'',
        ],
    ],
    'doctrine'           => [
        'connection'    => [
            // default connection name
            'orm_default' => [
                'driverClass' => 'Doctrine\DBAL\Driver\PDOMySql\Driver',
            ],
        ],
        'entitymanager' => [
            'orm_default' => [
                'connection'    => 'orm_default',
                'configuration' => 'orm_default',
            ],
        ],
    ],
    'phpSettings' => [
        'date.timezone' => 'Europe/Amsterdam',
    ],
];

You might notice that user and password details aren’t located in this part of configuration. This is stored in the local.php. When working on your own projects you’ll store usernames and passwords in this file. Make sure to never commit this to something that’s publicly available!

Now add the following configuration to the local.php file:

return [
    'application' => [
        'name' => 'Blog',
    ],
    'host' => 'blog.loc',
    'doctrine' => [
        'configuration' => [
            'orm_default' => [
                'generate_proxies' => false,
            ],
        ],
        'connection' => [
            'orm_default' => [
                'params' => [
                    'dbname'   => 'blog',
                    'user'     => 'blog',
                    'password' => 'blog',
                    'host'     => 'localhost',
                    'port'     => '3306',
                    'charset'  => 'utf8',
                ],
            ],
        ],
    ],
];

Now that we have the configuration needed to use Doctrine to manage the connection to the database, let’s also have Zend load the Doctrine modules required.

Modify the application configuration file, /config/application.config.php, to contain the following:

'modules' => [
    'Application',
    'DoctrineModule',
    'DoctrineORMModule',
],

In the file, the modules array should already be present, just add the DoctrineModule and DoctrineORMModule to it.

If you now refresh your application you should still be seeing the Skeleton Application homepage. If you see an error appear it could be that either the installed Zend or Doctrine modules installed via Composer are outdated. If so, try running composer update in your Terminal.