【问题标题】:Inject one service inside another service在另一个服务中注入一个服务
【发布时间】:2018-07-31 10:49:51
【问题描述】:

如何在 Symfony 3.4 中将一项服务注入到另一项服务中?

假设我有这个结构:

AppBundle
    Service
        ServiceOne.php
        ServiceTwo.php

我的 services.yml 看起来像:

services:
    ...
    AppBundle\Service\serviceOne:
        arguments: [...]

    service_one:
      alias: AppBundle\Service\serviceOne

    AppBundle\Service\ServiceTwo:
        arguments: ["@logger", "@service_one"]

这给了我一个错误:

[2018-07-31 10:37:43] request.CRITICAL: Uncaught PHP Exception Symfony\Component\Debug\Exception\ClassNotFoundException: "Attempted to load class "ServiceOne" from namespace "AppBundle\Service". Did you forget a "use" statement for another namespace?" at /symfony/var/cache/dev/ContainerKoj7t1p/getServiceOneService.php line 12 {"exception":"[object] (Symfony\\Component\\Debug\\Exception\\ClassNotFoundException(code: 0): Attempted to load class \"ServiceOne\" from namespace \"AppBundle\\Service\".\nDid you forget a \"use\" statement for another namespace? at /symfony/var/cache/dev/ContainerKoj7t1p/getServiceOneService.php:12)"} []

ServiceTwo.php:

<?php

namespace AppBundle\Service;

use Psr\Log\LoggerInterface;

class ServiceTwo {

    private $logger;
    private $serviceOne;

    public function __construct(LoggerInterface $logger, ServiceOne $serviceOne) {
        $this->logger = $logger;
        $this->serviceOne = $serviceOne;
    }
    ...

我已经尝试过这个solution 似乎它适用于旧版本的 symfony。

我也清除了缓存。

【问题讨论】:

  • services.yml(最后一行)中的单双引号是否只是一个错字?还有serviceOne类名的小写?
  • 是的,它是类型。我更新了。
  • 根据错误的位置,不是在ServiceTwo对象的构造里面,而是在你的getServiceOneService.php里面。
  • @EneaDume 对我来说看起来不像那个问题的重复,因为 OP 尝试完全按照那里的描述做,但仍然收到错误消息。

标签: symfony


【解决方案1】:
  1. 检查错别字。文件 ServiceOne.php 应该包含一个类 ServiceOne 并且应该在 service.yml 中命名为 ServiceOne(带有命名空间)
  2. 你不应该定义一个服务两次,AppBundle\Service\ServiceOne: ~ 将适合

  3. 您应该激活自动装配。这意味着您不需要配置这些服务。仅当您需要公共使用时。但是你仍然不需要配置参数

看这里自动装配:https://symfony.com/doc/current/service_container/autowiring.html 在这里自动加载:https://symfony.com/doc/3.4/service_container.html#injecting-services-config-into-a-service

【讨论】:

  • 2.使用此 `AppBundle\Service\ServiceOne: ~` 时如何将参数传递给 __construct 方法
  • 您已经在定义构造函数时完成了。 symfony 将从容器中查找类型并放入正确的依赖项。所以你没有别的事可做:__construct(LoggerInterface $logger, ServiceOne $serviceOne)
  • 谢谢,现在可以使用了。但我不太明白为什么它不适用于显式传递的参数。
  • 如果你想明确地解析它们,你需要将它们与洞命名空间/类名连接起来。不客气
  • 没有你输入:参数:[“@logger”,“@service_one”],我的意思是参数:[“@logger”,“AppBundle\\Service\\ServiceOne”]别忘了加倍反斜杠
猜你喜欢
  • 2013-12-22
  • 1970-01-01
  • 2014-01-27
  • 2012-08-01
  • 2023-03-11
  • 2023-03-16
  • 1970-01-01
  • 2022-12-20
相关资源
最近更新 更多