【问题标题】:PHP IoC cross dependenciesPHP IoC 交叉依赖
【发布时间】:2015-11-29 09:31:09
【问题描述】:

所以我们有一个容器、服务提供者,并且通过控制反转,我们可以做一些花哨的事情,比如:

public function __construct(CarServiceInterface $carService)
{
}

事情得到了很好的解决,因为在其他地方......

$container->bind(CarServiceInterface::class, function ()
{
    return new CarService();
});

假设汽车服务依赖于人工服务。那么……

    $container->bind(CarServiceInterface::class, function (Container $container)
    {
        return new CarService($container->make(HumanServiceInterface::class);
    });

嘿,这行得通。很酷。

但突然之间,人类需要汽车,而人类服务是这样构建的:

$container->bind(HumanServiceInterface::class, function (Container $container)
{
   return new HumanService($container->make(CarServiceInterface::class);
});

瞧,交叉依赖。

如何解决?

这是设计缺陷的结果吗?

谢谢!

【问题讨论】:

  • 相互依赖是不健康的

标签: php dependencies inversion-of-control containers ioc-container


【解决方案1】:

我认为这将被称为“循环依赖”(有关此内容的更多信息,请参阅 here)。

答案说没有办法做到这一点,并且使用循环依赖的唯一方法是使用 setter 注入,而不是通常的构造函数注入。

【讨论】:

  • 这是一个很好的答案。人类并不需要汽车,但如果有车,他们当然可以使用。
  • @watcher 谢谢,我同意,如果你将它与现实生活中的场景进行比较,它也很有意义。
猜你喜欢
  • 2013-07-18
  • 2019-07-11
  • 1970-01-01
  • 2013-05-08
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多