ZF2 – Sharing and reusing DB connection for dummies

Al-Punk

Still here
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 configuration can be invoked within each Module of ZF Application by including the following code in Modulename/Module.php
public function getServiceConfiguration()
{
return array(
'factories' => array(
'db-adapter' => function($sm) {
return $sm->get('db');
},
),
);
}
The following can then be retrieved at any place in Controller through:
$sm = $this->getServiceLocator();
$this->db = $sm->get('db-adapter');
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
),
),
);


xUy3pPG4UxE


Lexo origjinalin...
 
Top