如果我开发一个想要利用依赖容器的库,我认为容器implementation (php、symfony/依赖注入等等)应该由库的用户决定,最终将它传递给我,例如在类的构造函数中,如下所示:
public function __construct(string param, ?ContainerInterface $container = null)
{
$this->param = $param;
$this->container = $container;
}现在,如果我想向容器中添加一个条目,如果规范没有提供一个通用的方法,我如何能够以一种跨不同的PSR-11容器实现兼容的方式来实现它呢?使用php-di,我只需调用set方法:
public function __construct(string param, ?ContainerInterface $container = null)
{
$this->param = $param;
$this->container = $container; // I know it's a php-di container
$myDependency = Factory::buildMyDependency(); // dependency not instantiable through "new" keyword
$this->container->set(MyDependency::class, $myDependency)
}退一步,应该如何在许多共同居住的库之间共享一个容器?我是不是遗漏了什么?我不认为每个库都有自己的容器实现是可取的。
提前谢谢你。
发布于 2022-11-09 13:40:42
我无意中发现了同样的问题,而且也惊讶于set方法没有包括在内。
在本文中解释了原因:https://www.php-fig.org/psr/psr-11/meta/#31-goals
简而言之:容器接口的目标受众是库或框架的作者,而不是应用程序本身负责填充容器的具体应用程序的作者。这就是为什么没有setter方法的原因。
https://stackoverflow.com/questions/61504435
复制相似问题