簡體   English   中英

symfony 4.1:不存在此類服務

[英]symfony 4.1: no such service exists

所以我上周創建了一個新的 Symfony 4.1 項目,並且一直在努力工作,沒有任何問題。 直到昨天我開始使用一些第三方依賴項。 我使用composer require guzzlehttp/guzzle guzzle 安裝了 Guzzle 客戶端。 據我所知,這安裝了 package 就好了。

但是,當我嘗試將此服務注入代碼(事件或命令)中的構造函數時,我收到錯誤消息: 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,而不是 package。 我不知道作曲家足夠聰明,可以通過它提供的類識別 package,所以我檢查了......它不能,只給出 package 名稱建議。

確保您了解什么是作曲家 package。

Guzzle 服務不是唯一不起作用的服務,這只是一個示例。

您沒有 Guzzle 服務。 你只有 guzzle 庫和它的類。 服務需要一個服務定義,就像你寫的那樣。

您提到的 Doctrine 等其他服務正在運行,因為它們是提供服務定義的捆綁包。

要么使用捆綁軟件,要么使用庫,然后自己連接。

在 guzzle 的情況下,我不會使用捆綁包。 再說一次,我不會再直接使用 guzzle,而是使用 HTTPlug。 (捆綁: https://github.com/php-http/HttplugBundle ,庫: https://github.com/php-http/httplug

就我而言,我只需要重新生成優化的自動加載文件。

所以使用composer dump-autoload為我解決了這個問題。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM