所以我现在有一个非常简单的服务。这是我的 services.yaml:
# This file is the entry point to configure your own services.
# Files in the packages/ subdirectory configure your dependencies.
# Put parameters here that don't need to change on each machine where the app is deployed
# https://symfony.com/doc/current/best_practices.html#use-parameters-for-application-configuration
parameters:
imports:
- resource: myservice.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.
# makes classes in src/ available to be used as services
# this creates a service per class whose id is the fully-qualified class name
App\:
resource: '../src/'
exclude:
- '../src/DependencyInjection/'
- '../src/Entity/'
- '../src/Kernel.php'
# add more service definitions when explicit configuration is needed
# please note that last definitions always *replace* previous ones
文件 myservice.yaml 是:
services:
service.http_client:
class: GuzzleHttp\Client
public: true
arguments:
-
timeout: 2.0
base_uri: "%env(BASE_URI)%"
handler: GuzzleHttp\HandlerStack
headers:
X-Api-Key: "%env(API_KEY)%"
service.service_client:
class: Service\V1alpha\ServiceClient
arguments:
- '%env(BASE_URI)%'
- '@deeplink.http_client'
- ~
- ~
- ''
service:
class: App\Service\Service
public: true
arguments:
- "@service.service_client"
当我尝试在我的 Controller 中使用它时,例如:
public function __construct(private readonly Service $deeplinkService)
{}
它总是失败,说 Service\V1alpha\ServiceClient
不存在这样的服务。所以这个服务显然存在于 ma vendor
文件夹中,并且命名空间是正确的。这里的 Autowiring 有什么问题?
最佳答案
我看到一些不必要的东西:
- 停止为类声明别名,直接使用它。
- 仅声明您需要的参数 ( https://symfony.com/doc/current/service_container.html#choose-a-specific-service )
- 避免将类声明为“public”
services:
Service\V1alpha\ServiceClient:
arguments:
$uri: '%env(BASE_URI)%'
$ĥttpClient: '@deeplink.http_client'
并且您的类似乎没有在 services.yaml 中声明(它已经在 App\:
和 _defaults
中完成),容器将在那里为你。
public function __construct(private readonly ServiceClient $deeplinkService)
{}
关于php - Symfony 6 服务 Autowiring ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/76826350/