symfony 4.1:不存在这样的服务

symfony 4.1: no such service exists

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

但是,当我随后尝试将此服务注入我的代码(事件或命令)中的构造函数时,我收到错误消息: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 一起工作?

composer require GuzzleHttp\Client

您似乎想要 class,而不是包裹。我不知道作曲家足够聪明,可以通过提供的 classes 来识别包,所以我检查了......它不能,只提供包名称建议。

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

The Guzzle service is not the only one that doesn't work, this is just an example.

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

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

要么使用捆绑包,要么使用库,然后自己连接。

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