依赖性解决设计模式

时间:2014-03-12 12:33:19

标签: php oop dependency-injection module

1 个答案:

答案 0 :(得分:0)

IoC容器完全解决方案。

  

我想用明确定义的接口注入依赖项,而不是从DI容器或服务定位器中提取它们

然后不要将容器用作服务定位器。这正是DI容器的用途。

以下是使用PHP-DI的示例:

$containerBuilder = new ContainerBuilder();
$container = containerBuilder->build();

// Configure RestApi\EntryPoint to use for Contract\EntryPoint
$container->set(Contract\EntryPoint::class, \DI\link(RestApi\EntryPoint::class));

// Configure BusinessLogic\Application to use for Contract\Application
$container->set(Contract\Application::class, \DI\link(BusinessLogic\Application::class));

// Run
$entryPoint = $container->get(Contract\EntryPoint::class);
$entryPoint->handleRequest();

当然我的例子并不完美。我建议将配置部分与执行部分分开。我会将配置放在配置文件(look here for how)中。

重要:是的,在该示例中,我从容器中获取内容。这是特殊的。在您的申请中,这应该只发生一次或两次。

您必须在应用程序的根目录(即应用程序的入口点)的某个位置使用容器来构造对象图(或依赖关系图)。

我不建议您每次需要依赖时在容器上调用get()。我建议您使用依赖注入,并且只在应用程序的入口点调用get()


使用工厂定义的示例:

$container->set(Contract\EntryPoint::class, \DI\factory(function (Container $c) {
    return new RestApi\EntryPoint($c->get('some.parameter'));
}));