【发布时间】:2018-08-27 11:42:35
【问题描述】:
我想将我最近设置的 Symfony 4 项目与 PHP-DI 6 和 PHP-DI Symfony Bridge 3 一起使用。
我的项目结构如下所示:
|-config
|---dependencies
|-----common.php
...
|-src
...
|-Interop
|---Api
|---Website
|-----Controller
|-------IndexController.php
...
|---Services
|-----Dummy
|-------FooService.php
|-------FooServiceInterface.php
...
|-Kernel.php
FooService 和 BuzService 类实现了 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();
}
一切似乎都按照PHP-DI Symfony Bridge documentation设置好了。
如果只有FooServiceInterface 的一个实现,一切正常。但是当我再添加一个时,例如:
class BuzService implements FooServiceInterface
我收到一个错误:
运行时异常
无法自动装配服务 “App\Interop\Website\Controller\IndexController”:参数 方法“__construct()”的“$fooService”引用接口 "App\Services\Dummy\FooServiceInterface" 但不存在这样的服务。 您可能应该将此接口别名为这些现有接口之一 服务:“App\Services\Dummy\BuzService”, “应用\服务\虚拟\FooService”。你创建了一个类 实现了这个接口?
为什么会出现此错误以及如何使此结构正常工作?
【问题讨论】:
标签: symfony dependency-injection symfony4 php-di