Configuring database adapters within Zend Framework 3 is similar to how they are configured in earlier versions of Zend.
Within your project root, a config/autoload/global.php
and config/autoload/local.php.dist
file should exist. You should recognise these files from ZF2.
You can add database adapters to either of these files (after you have renamed the local.php.dist file to local.php). The difference between the two files is that global.php
is included in version control whereas local.php
is not.
This means that if you database requires credentials to connect to, you should add them into the local.php
file and therefore not commit them using a VCS.
The database credentials might look like the following.
// config/autoload/local.php
return [
'db' => [
'driver' => 'Pdo',
'dsn' => 'mysql:dbname=zend_db;host=localhost',
'username' => 'zf3',
'password' => 'zf3test',
],
];
A db
database adapter has been defined above. Within your service factories, you may retrieve the default adapter from your application container using the class name Zend\Db\Adapter\AdapterInterface:
use Zend\Db\Adapter\AdapterInterface;
function ($container) {
return new SomeServiceObject($container->get('db');
}
There may be scenarios that require you to add multiple database adapters. For example, a database that requires read only access whilst another requires write access.
To add multiple adapter configuration, create an adapters
configuration key within the already defined db
key.
return [
'db' => [
'adapters' => [
'WriteAdapter' => [
'driver' => 'Pdo',
'dsn' => 'mysql:dbname=application;host=write.example.com;charset=utf8',
],
'ReadOnlyAdapter' => [
'driver' => 'Pdo',
'dsn' => 'mysql:dbname=application;host=read.example.com;charset=utf8',
],
],
],
];