I want to have access to database config set in global config file within my model. In ZF2 controllers we can load configs using getServiceLocator
method, but how can i do this in my Model class ? here is my Model class:
class BaseModel extends AbstractTableGateway
{
public function __construct()
{
$this->adapter = new Adapter(array(
'driver' => 'Pdo_Mysql',
'database' => 'mydbname',
'username' => 'root',
'password' => 'root'
));
}
}
I just want to load 'db' array config ( located in global config file) and replace with this input array as a Adapter class input parameters.
Here is my global config file:
return array(
"db" => array(
"driver" => "Pdo_Mysql",
"dsn" => "mysql:dbname=mydbname;host=localhost",
"username" => "root",
"password" => "root"
),
"service_manager" => array(
"factories" => array(
"dbFactory" => "Zend\Db\Adapter\AdapterServiceFactory",
)
)
);
If you need to modify the DbAdapter
config (the database you are connecting to) you'll need to create a different instance of the adapter and then inject the adapter that into your 'model'
class FooModel extends AbstractTableGateway
{
public function __construct($dbAdapter)
{
$this->adapter = $adapter;
}
}
Then create the adapter service factories
public function getServiceConfig()
{
return array(
'factories' => array(
// Standard database adapter
'dbAdapter1' => function($sm) {
$config = $sm->get('config');
return new \Zend\Db\Adapter\Adapter($config['db']);
},
// Another db adapter using different config
'dbAdapter2' => function($sm) {
$config = $sm->get('config');
return new \Zend\Db\Adapter\Adapter($config['db2']);
},
// The model that requires a different database
// adapter to be injected
'FooModel' => function($sm) {
$adapter = $sm->get('dbAdapter2');
return new Model\FooModel($adapter);
},
),
);
}
You can then add all the config to the db2
key in either global or module.config.php
.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.