ZF2 – Sharing and reusing DB connection for dummies

zf2

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

<?php
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
        ),
    ),
);

5 Comments

  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’);

    Reply
  2. Mandi says:

    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!

    Reply
  3. runphp says:

    Additional information:
    Zend\ServiceManager\Exception\ServiceNotFoundException

    File:

    /home/wwwroot/zf2/jj/vendor/zendframework/zendframework/library/Zend/ServiceManager/ServiceManager.php:453

    Message:

    Zend\ServiceManager\ServiceManager::get was unable to fetch or create an instance for db

    why? thx

    Reply
  4. Fawad Ghafoor says:

    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

    Reply

Trackbacks for this post

  1. ZF2 access to database connection in external classes | Jisku.com - Developers Network

Leave a Comment

Powered by WordPress | Deadline Theme : An AWESEM design