(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 ), ), );