如何使用PHP-DI Symfony Bridge作为控制器?

时间:2018-03-18 23:59:14

标签: symfony dependency-injection symfony4 php-di

我想使用我最近设置的PHP-DI 6和PHP-DI Symfony Bridge 3的Symfony 4项目。

我的项目结构如下所示:

|-config
|---dependencies
|-----common.php
...
|-src
...
|-Interop
|---Api
|---Website
|-----Controller
|-------IndexController.php
...
|---Services
|-----Dummy
|-------FooService.php
|-------FooServiceInterface.php
...
|-Kernel.php

课程FooServiceBuzService实施FooServiceInterface

/config/dependencies/common.php

return [
    IndexController::class => DI\create(IndexController::class),
    FooServiceInterface::class => DI\create(FooService::class),
];

IndexController 获取FooServiceInterface注入的实例。

public function __construct(FooServiceInterface $fooService)
{
    $this->fooService = $fooService;
}

Kernel 扩展DI\Bridge\Symfony\Kernel并实现其buildPHPDIContainer(...)

protected function buildPHPDIContainer(PhpDiContainerBuilder $builder)
{
    $builder->addDefinitions(__DIR__ . '/../config/dependencies/common.php');
    return $builder->build();
}

Everythings似乎是根据PHP-DI Symfony Bridge documentation设置的。

如果FooServiceInterface只有一个实现,那么一切正常。但是当我再添加一个时,例如:

class BuzService implements FooServiceInterface

我收到错误:

  

的RuntimeException

     

无法自动连接服务   “App \ Interop \ Website \ Controller \ IndexController”:参数   方法“__construct()”的“$ fooService”引用接口   “App \ Services \ Dummy \ FooServiceInterface”但不存在此类服务。   您应该将此接口别名为其中一个现有接口   服务:“App \ Services \ Dummy \ BuzService”,   “应用程序\ SERVICES \虚拟\ FooService接口”。你创建了一个类吗?   实现这个接口?

为什么我会收到此错误&如何使这个结构正常工作?

1 个答案:

答案 0 :(得分:2)

此错误消息看起来像是Symfony错误消息,而不是PHP-DI消息。

我猜测Symfony扫描所有课程的自动装配,包括你的控制器(即使它没有必要)。

这是我第一次听到这个,我想你需要完全禁用Symfony的自动装配,还是某些特定的文件夹?如果您可以向PHP-DI的文档发送拉取请求,那将是非常棒的:)