【问题标题】:Dependency Injection not working, but defined manually依赖注入不起作用,但手动定义
【发布时间】:2018-10-05 13:55:03
【问题描述】:

我是 Symfony 的新手,并尝试使用来自 gos/web-socket-bundle 的 ClientManipulatorInterface 服务。 我的问题是,即使我手动配置参数,Symfony 也会返回错误。

我总是收到此错误:无法自动连接服务“Foo\Bar\Controller\testTopic”:方法“__construct()”的参数“$clientManipulator”引用接口“Gos\Bundle\WebSocketBundle\Client\ClientManipulatorInterface”但没有服务存在。你也许应该
将此接口别名为现有的“gos_web_socket.websocket.client_manipulator”服务。

这是我的 service.yaml:

services:
    test_topic:
        class: Foo\Bar\Controller\testTopic
        tags:
            - { name: gos_web_socket.topic }
        arguments:
            - '@gos_web_socket.websocket.client_manipulator'

这是我的 PHP 类:

namespace Foo\Bar\Controller;

use Gos\Bundle\WebSocketBundle\Client\ClientManipulatorInterface;
use Gos\Bundle\WebSocketBundle\Topic\TopicInterface;

class testTopic implements TopicInterface {

    /**
     * @var ClientManipulatorInterface
     */
    protected $clientManipulator;

    /**
     * testTopic constructor.
     * @param ClientManipulatorInterface $clientManipulator
     */
    public function __construct(ClientManipulatorInterface $clientManipulator) {
        $this->clientManipulator = $clientManipulator;
    }

    ...

【问题讨论】:

  • 我知道您已经接受了答案,但您的配置的实际问题是您使用了 test_topic 的服务 ID 而不是 Foo\Bar\Controller\testTopic。错误消息实际上来自 autowire,因为它会扫描您的所有类并尝试将它们自动转换为服务。 Autowire 使用类名,因此查看是否手动定义了服务。在您的情况下,它找不到您的服务,因此它尝试创建它并遇到接口问题。换句话说,将服务 id 更改为类名,您的原始配置就可以工作了。

标签: php symfony service dependency-injection


【解决方案1】:

您需要将 ClientManipulatorInterface 别名为它的其中一个实现,Symfony 才能正确地自动连接依赖项:

services:
    Gos\Bundle\WebSocketBundle\Client\ClientManipulatorInterface: '@gos_web_socket.websocket.client_manipulator'

    Foo\Bar\Controller\testTopic:
        autowire: true
        tags:
            - { name: gos_web_socket.topic }

之后清除缓存!

【讨论】:

  • 我希望它会自动完成,因为它是在 gos/web-socket-bundle 中定义的。现在我也在我的 services.yaml 中定义了它并且它可以工作。谢谢。
  • 捆绑包的 service-definitions 不包含接口别名 - 这就是开箱即用无法自动连接的原因。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-06-12
  • 1970-01-01
  • 2023-02-24
  • 2016-11-09
  • 1970-01-01
  • 2020-06-19
相关资源
最近更新 更多