在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',
),
)
),
在控制器工厂中,我可以通过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,
],
],
尝试在我的$container->get('db1')
中使用AlbumTableFactory
获取dbAdapter时出现此错误:
Unable to resolve service "db1 to a factory; are you certain you provided it during configuration?
答案 0 :(得分:1)
确保您已将Zend\Db\Adapter\AdapterAbstractServiceFactory
添加到ServiceManager配置的abstract_factories
数组中。
此抽象工厂负责实例化各个数据库适配器。另外,检查您的Album\Model\AlbumTable
工厂是否使用正确的名称检索数据库适配器。
答案 1 :(得分:1)
好的,我终于解决了这个问题。
正如@Pieter所提到的,我需要config.php
中的以下数组内容:
'service_manager' => [
'abstract_factories' => [
\Zend\Db\Adapter\AdapterAbstractServiceFactory::class,
],
],
此外,我不得不改变我的班级和依赖工厂相互交谈的过程。
AlbumControllerFactory
被调用并获得依赖AlbumTable
服务($container->get(AlbumTable::class);
),然后触发AlbumTableFactory
AlbumTableFactory
然后使用AlbumTable
$tableGateway = $container->get(AlbumTableGateway::class);
准备构造函数注入
AlbumTableFactory
和AlbumTableGatewayFactory
的逻辑合并为一个AbstractFactoryInterface
(我完全删除了AlbumTableGatewayFactory)// AlbumTableFactory implements AbstractFactoryInterface
public function __invoke(ContainerInterface $container, $requestedName, array $options = null)
{
$dbAdapter = $container->get('db1');
$resultSetPrototype = new ResultSet();
$resultSetPrototype->setArrayObjectPrototype(new Album());
$tableGateway = new TableGateway('album', $dbAdapter, null, $resultSetPrototype);
return new AlbumTable($tableGateway);
}