[英]PHP-DI Potentially polymorphic call when using the set method
当我尝试在 PHP-DI 容器中设置新值时,我收到来自 PHPStorm 的意外警告。
鉴于以下代码:
function inject(Psr\Container\ContainerInterface $container){
$container->set(RandomClass::class, new RandomClass());
}
$container = new DI\Container(); class is instantiated
inject($container);
触发了以下警告
潜在的多态调用。 在其层次结构中没有成员
我理解警告的含义,但我不明白为什么会弹出它,特别是因为我在查看 Google 和 SO 时没有发现任何这种情况,并且文档没有提到它。
有什么我遗漏的,还是“误报”?
鉴于以下代码(与我使用的代码非常相似)
function inject(Psr\Container\ContainerInterface $container){
$container->set(RandomClass::class, new RandomClass());
}
$container = new DI\Container(); class is instantiated
inject($container);
$container->set(...)
调用将触发以下警告
潜在的多态调用。 在其层次结构中没有成员
这是意料之中的,因为Psr\\Container\\ContainerInterface
仅包含以下方法的定义
get($id)
has($id)
此问题的两种可能解决方案:
Container
和“使用命名空间”,这将使更改为新的容器包更容易(因为这仍然是 PSR 背后的目标,被几乎可以热插拔封装)。Psr\\Container\\ContainerInterface
的自定义接口, Psr\\Container\\ContainerInterface
添加所需的方法。 或者,最终,您可以尝试使PHP-FIG扩展PSR-11标准以包含标准set($id, $value)
方法。
set()
方法不是Psr\\Container\\ContainerInterface
。
如果您想使用该方法,则不能针对接口键入提示,因为您的代码明确需要一个 PHP-DI 实例。
你的代码不必是通用的,不要想太多。 PSR 主要用于框架和库(需要与多个容器兼容),而不是最终用户。
在您切换容器库的那一天,您将有更多复杂的事情要做,而不仅仅是替换set()
调用。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.