symfony 4.1:不存在此类服务

时间:2018-07-11 08:06:15

标签: php symfony symfony4

因此,我上周创建了一个新的Symfony 4.1项目,并且一直在努力进行,没有任何问题。直到昨天,当我开始使用一些第三方依赖项时。我使用composer require guzzlehttp/guzzle安装了Guzzle Client。据我所知,这安装了软件包。

但是,当我随后尝试将此服务注入代码(事件或命令)的构造函数中时,出现错误消息:Cannot autowire service "App\xxx\Command\testCommand": argument "$client" of method "__construct()" references class "GuzzleHttp\Client" but no such service exists.

Guzzle服务不是唯一一个不起作用的服务,这只是一个示例。对我来说,很奇怪的是,我有很多可以正常工作的依赖项,例如Doctrine DocumentManager,JMS序列化程序和NelmioApiDocBundle。

到目前为止,我已经尝试过(实际上是半解决了问题)的方法是将服务名称添加到我的services.yaml文件中:

services:
    # default configuration for services in *this* file
    _defaults:
        autowire: true      # Automatically injects dependencies in your services.
        autoconfigure: true # Automatically registers your services as commands, event subscribers, etc.
        public: false       # Allows optimizing the container by removing unused services; this also means
                        # fetching services directly from the container via $container->get() won't work.
                        # The best practice is to be explicit about your dependencies anyway.   

    GuzzleHttp\Client:  <-- Adding this makes it work flawlessly.

此解决方案的问题在于,我最终会在我的services.yaml文件中添加数百个服务,以使其正常工作。在我看来,这不是最佳解决方案。

所以我的问题是我该如何以最优雅的方式解决这个问题。这是我在项目中做错的事情吗?是否必须在供应商方面解决?如果是这样,如何使其与Symfony 4.1一起使用?

1 个答案:

答案 0 :(得分:1)

  

composer require GuzzleHttp\Client

似乎您正在尝试要求一个类,而不是一个包。我不知道composer是否足够聪明,可以通过提供的类来识别软件包,因此我检查了……它不能,仅给出软件包名称建议。

确保您了解什么是作曲家软件包。

  

Guzzle服务不是唯一一个不起作用的服务,这只是一个例子。

您没有Guzzle服务。您只有带有类的guzzle库。服务需要一个服务定义,就像您编写的那样。

您提到的诸如Doctrine之类的其他服务正在运行,因为它们是捆绑包,提供了服务定义。

要么使用捆绑软件,要么使用库,然后将其自己连接起来。

在大吃一惊的情况下,我不会使用捆绑包。再说一次,我不再直接使用guzzle,而是HTTPlug。 (捆绑:https://github.com/php-http/HttplugBundle,图书馆:https://github.com/php-http/httplug