【问题标题】:How to use the PHP-DI Symfony Bridge for Controllers?如何为控制器使用 PHP-DI Symfony Bridge?
【发布时间】: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

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();
}

一切似乎都按照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


    【解决方案1】:

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

    我猜 Symfony 会扫描你所有的类以进行自动装配,包括你的控制器(尽管这不是必需的)。

    这是我第一次听说这个,我猜你需要完全禁用 Symfony 的自动装配,或者某些特定文件夹?如果您可以向 PHP-DI 的文档发送拉取请求,那就太棒了:)

    【讨论】:

    • 你好,马修!谢谢您的回答!现在它正在工作。我必须在我的代码中修复两个地方: 1. Symfony:在services.yaml 中至少必须进行以下更改之一:将services.autoconfigure(不是service.autowire)设置为false 和/或b。将Controller 目录的路径添加到service.App\.exclude 列表(或完全禁用services.App)。 2. PHP-DI:我使用DI\create(...) 并收到错误“[...] 无法解决:参数 [...] 没有定义或猜测的值”。此调用必须替换为 DI\get(...)
    • 稍后我会向 PHP-DI 的文档发送拉取请求。
    猜你喜欢
    • 1970-01-01
    • 2012-04-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-04-02
    • 2019-08-11
    • 2020-11-03
    • 1970-01-01
    相关资源
    最近更新 更多