在 ZF2 中,可以在 module.config.php
中配置多个适配器,如下所示:
'db' => array(
'adapters'=>array(
'db1' => array(
'driver' => 'Pdo',
'dsn' => 'mysql:dbname=zf2;host=localhost',
'driver_options' => array(
PDO::MYSQL_ATTR_INIT_COMMAND => 'SET NAMES \'UTF8\''
),
'username' => 'zf2',
'password' => 'zf2test',
),
'db2' => array(
'driver' => 'Pdo',
'dsn' => 'mysql:dbname=zf1;host=localhost',
'driver_options' => array(
PDO::MYSQL_ATTR_INIT_COMMAND => 'SET NAMES \'UTF8\''
),
'username' => 'zf1',
'password' => 'zf1test',
),
)
),
在 Controller 工厂中,我可以通过 ServiceManager 获取它们:
class AlbumControllerFactory implements FactoryInterface
{
public function createService(ServiceLocatorInterface $serviceLocator)
{
$albumTable = $serviceLocator->getServiceLocator()->get('Album\Model\AlbumTable');
$db1Adapter = $serviceLocator->getServiceLocator()->get('db1');
$db2Adapter = $serviceLocator->getServiceLocator()->get('db2');
return new AlbumController($albumTable, $db1Adapter, $db2Adapter);
}
}
现在我尝试在 Zend Framework 3 中执行相同的操作 - 但此嵌套数组配置不起作用:
Fatal error: Uncaught exception 'Zend\Db\Adapter\Exception\InvalidArgumentException' with message 'createDriver expects a "driver" key to be present inside the parameters' in /var/www/USER/teckert/zf3/vendor/zendframework/zend-db/src/Adapter/Adapter.php:262
我认为在 ZF 2 中,当 dbAdapter 尝试创建驱动程序时,adapters
键已经被处理 - 但这在 ZF 3 中不会发生。
热烈欢迎任何提示...
zend-db with the adapters section的手册对我来说还不够清楚
编辑
根据this doc我已将以下代码片段添加到全局配置文件中:
'service_manager' => [
'abstract_factories' => [
\Zend\Db\Adapter\AdapterAbstractServiceFactory::class,
],
],
在我的 AlbumTableFactory
中尝试使用 $container->get('db1')
获取 dbAdapter 时,出现以下错误:
Unable to resolve service "db1 to a factory; are you certain you provided it during configuration?
最佳答案
确保您已将 Zend\Db\Adapter\AdapterAbstractServiceFactory
添加到 ServiceManager 配置的 abstract_factories
数组中。
该抽象工厂负责实例化各个数据库适配器。另外,检查您的 Album\Model\AlbumTable
工厂是否检索具有正确名称的数据库适配器。
关于php - ZF3 多数据库适配器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38526146/