ZF2 – Sharing and reusing DB connection for dummies

(Post has been updated after comment from Flamur on a unneccessary code in Module/Module.php)
While we were used to pass the DB-Connection to a Register or later this practice was improved by retrieving it from the Bootstrap in Zend Framework 1, the ZF2 has a new service layer which looks like a new commodity. I am referring to the ServiceManager, which also something like a registry for different object instances.

In ZF2, the DB credentials are usually stored in the ./config/autoload/ directory. Normally all files within this directory will be loaded by the ModuleManager (you don’t need to care much at this time). The file global.php (or db.php) should look like this:

return array(
    'service_manager' => array(
        'factories' => array(
            'Zend\Db\Adapter\Adapter' => 'Zend\Db\Adapter\AdapterServiceFactory',
        'aliases' => array(
            'db' => 'Zend\Db\Adapter\Adapter',
    'db' => array(
        'driver'    => 'pdo',
        'dsn'       => 'mysql:dbname=DBNAME;host=HOSTNAME',
        'username'  => 'USERNAME',
        'password'  => 'USERPASS',
    	'driver_options' => array(
                        PDO::MYSQL_ATTR_INIT_COMMAND => 'SET NAMES 'UTF8''

The following can then be retrieved at any place in Controller through:

 $this->db = $this->getServiceLocator()->get('db');

And if you are using 3rd party modules from different vendors, who require access to your DB-adapter, you can just add the following to their config/autoload/ directory:

return array(
    'service_manager' => array(
        'aliases' => array(
            'vendor_or_any_any_name_for_zend_db_adapter' => 'db', //Same as the alias in our main global.conf

10 Replies to “ZF2 – Sharing and reusing DB connection for dummies”

  1. Hi Mandi, why invoke/include on the Module/Module.php? You can just skip that part since you have created an alias on the adapter and just retrieve that instance from the controller by using this code: $this->getServiceLocator()->get(‘db’);

  2. Flamur you are right! I was not sure that I can invoke it directly from the Controller.
    I tested and it works, will update the post soon! Post updated!

  3. Additional information:




    ZendServiceManagerServiceManager::get was unable to fetch or create an instance for db

    why? thx

  4. Hello Mandi!
    very nice thank you! how would i go further i mean how to create object of my Albumtable.php classe through your way because your way seems different from official documentation.

    Thanking you in anticipation

  5. How do I access the Database in a Model file? Do I have to pass around the db object from the controller to the model or is there an easier way to do that?


    1. Sorry, I am not developing in ZF2 right now. It is a pretty confusing framework and I would recommend you switch to one which makes your life easier and not miserable.

Comments are closed.