Database Adapters in Zend Framework 2

As with many web applications, at some point we require a connection to the database. Database Adapters in Zend Framework 2 are fairly simple to implement, and this can be seen below by viewing the following steps below.

As some parts of the database configuration is often specific to your local environment, parts of the config should belong in different files.

For example, you could add the below in the config/autoload/global.php file.

// config/autoload/global.php
return array(
    'db' => array(
        'driver'         => 'Pdo',
        'dsn'            => 'mysql:dbname=zend_db;host=localhost',
    ),
    'service_manager' => array(
        'aliases' => array(
            'db' => 'Zend\Db\Adapter\Adapter',
        ),
    ),
);

And your local environment configuration belonging in config/autoload/local.php. If this file does not exist, a local.php.dist should be within the same directory. Simply rename this file and edit as necessary.

Local configuration for databases could include the database username and password, for example.

// config/autoload/local.php
return array(
    'db' => array(
        'username' => 'YOUR USERNAME HERE',
        'password' => 'YOUR PASSWORD HERE',
    ),
);

Any .dist extension files provided by ZF2 should not contain any sensitive information. As a precaution, The skeleton application ensures that these files are added to .gitignore which prevents sensitive credentials from accidentally being committed into version control.

If using the mysqli database drive, the buffer_results option should be added to the configuration, otherwise you will only be able to retrieve the first result from a set.

// config/autoload/global.php
return array(
    'db' => array(
        'driver'         => 'Pdo',
        'dsn'            => 'mysql:dbname=zend_db;host=localhost',
        'options'        => array(
            'buffer_results' => true
        ),
    ),
    'service_manager' => array(
        'aliases' => array(
            'db' => 'Zend\Db\Adapter\Adapter',
        ),
    ),
);

Most of the controllers you create within the ZF2 application extend the Zend\Mvc\Controller\AbstractActionController class which in turns extends the Zend\Mvc\Controller\AbstractController class.

The AbstractController class has access to the getServiceLocator() method. This means that you can retrieve the ‘db’ service created in the configuration from a controller by using the following line.

$dbAdapter = $this->getServiceLocator()->get('Zend\Db\Adapter\Adapter');

The same can be said for any other classes within your application that can get a service. You’ll then be able to manipulate your database information as required.

Note: This article is based on ZF version 2.4.