gpt4 book ai didi

php - ServiceLocatorAwareInterface 在运行模块测试时混淆 DI 容器

转载 作者:行者123 更新时间:2023-12-04 05:32:16 25 4
gpt4 key购买 nike

我有一个正在为其编写测试的新模块。
该模块包含一个实现 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 测试版期间的相似,您应该能够在您的 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com