问题描述
我想将最近设置的Symfony 4项目与PHP-DI 6和PHP-DI Symfony Bridge 3一起使用.
I want to use my recently set up Symfony 4 project with PHP-DI 6 and 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
/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文档设置的. a>.
Everythings seems to be set up according to the PHP-DI Symfony Bridge documentation.
如果仅FooServiceInterface
的一种实现,则一切正常.但是当我再添加一个时,例如:
Everything works fine, if there is only one implementation of the FooServiceInterface
. But when I add a further one, e.g.:
class BuzService implements FooServiceInterface
我得到一个错误:
无法自动连线服务 "App \ Interop \ Website \ Controller \ IndexController":参数 方法"__construct()"的"$ fooService"引用接口 "App \ Services \ Dummy \ FooServiceInterface",但不存在此类服务. 您可能应该将此接口别名为现有接口之一 服务:"App \ Services \ Dummy \ BuzService", "App \ Services \ Dummy \ FooService".您是否创建了一个课程 实现此接口?
Cannot autowire service "App\Interop\Website\Controller\IndexController": argument "$fooService" of method "__construct()" references interface "App\Services\Dummy\FooServiceInterface" but no such service exists. You should maybe alias this interface to one of these existing services: "App\Services\Dummy\BuzService", "App\Services\Dummy\FooService". Did you create a class that implements this interface?
为什么会出现此错误&如何使该结构正常工作?
推荐答案
此错误消息看起来像是Symfony错误消息,而不是PHP-DI错误消息.
This error message looks like a Symfony error message, not a PHP-DI one.
我猜想Symfony会扫描所有类以进行自动装配,包括控制器(即使不是必需的).
I'm guessing that Symfony scans all your classes for autowiring, including your controller (even though it's not necessary).
这是我第一次听到此消息,我想您需要完全禁用Symfony的自动装配功能,还是要禁用某些特定的文件夹?如果您可以向PHP-DI的文档发送拉取请求,那就太好了:)
This is the first time I hear of this, I guess you need to disable Symfony's autowiring entirely, or for some specific folders? If you can send a pull request to PHP-DI's documentation that would be awesome :)
这篇关于如何将PHP-DI Symfony Bridge用于控制器?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!