我想在我的模型中访问全局配置文件中的数据库配置集。在ZF2控制器中,我们可以使用getServiceLocator
方法加载配置,但是如何在我的Model类中执行此操作?这是我的Model类:
class BaseModel extends AbstractTableGateway
{
public function __construct()
{
$this->adapter = new Adapter(array(
'driver' => 'Pdo_Mysql',
'database' => 'mydbname',
'username' => 'root',
'password' => 'root'
));
}
}
我只想加载'db'数组配置(位于全局配置文件中)并将此输入数组替换为Adapter类输入参数。
这是我的全局配置文件:
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",
)
)
);
答案 0 :(得分:0)
如果您需要修改DbAdapter
配置(您要连接的数据库),您需要创建一个不同的适配器实例,然后注入适配器进入你的模型'
class FooModel extends AbstractTableGateway
{
public function __construct($dbAdapter)
{
$this->adapter = $adapter;
}
}
然后创建适配器服务工厂
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);
},
),
);
}
然后,您可以将全部配置添加到全局或db2
中的module.config.php
键。