将一项服务注入另一项服务

时间:2018-07-31 10:49:51

标签: symfony

如何在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。

我也清除了缓存。

1 个答案:

答案 0 :(得分:2)

  1. 检查Typos。文件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