我有一个新模块,正在为其编写测试。 该模块包含一个实现 ServiceLocatorAwareInterface 的类,因为它需要使用 DI 容器创建其他对象。在骨架应用程序中运行时一切正常,但是在运行模块测试时我得到以下结果:
Zend\Di\Exception\RuntimeException: Invalid instantiator of type "NULL" for "Zend\ServiceManager\ServiceLocatorInterface"
研究了一下,我发现 DI 容器尝试创建一个“ServiceLocatorAwareInterface”类型的新对象,这当然是错误的。
在测试 Bootstrap 中进行更多挖掘,我发现添加以下行可以解决问题,因为 DI 现在知道要为该接口(interface)实例化什么类。
$di->instanceManager()->addTypePreference('Zend\ServiceManager\ServiceLocatorInterface', new \Zend\ServiceManager\ServiceManager());
我不确定这是否是问题的最佳解决方案,因为我传递的 ServiceManager 是一个虚拟的。
大家还有其他想法吗?
最佳答案
是的,您正朝着正确的方向前进。 (参见the preferences documentation)
现在没有多少人使用 DI 来支持 ServiceManager(包括我自己),但如果 DI 的配置与 ZF2 beta 期间的配置类似,您应该能够添加一个“首选项”部分你的 DI 配置如下:
'di' => array(
'instance' => array(
'preferences' => array(
'My_Interface' => 'My_Implementation_Or_Alias',
)
)
)
此配置 block 可以替换您对 $di->instanceManager()->addTypePreference() 的调用
查看当前文档,并模仿示例 here ,您可能会使用 ZF2 官方版本成功定义 DI 配置,如下所示:
$di = new Zend\Di\Di;
$di->configure(new Zend\Di\Config(array(
'instance' => array(
'preferences' => array(
'My_Interface' => 'My_Implementation_Or_Alias',
)
)
)));
关于php - ServiceLocatorAwareInterface 在运行模块测试时混淆 DI 容器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12426744/