代码之家  ›  专栏  ›  技术社区  ›  Joozty

在另一个服务中注入一个服务

  •  1
  • Joozty  · 技术社区  · 6 年前

    在symfony 3.4中,如何将一个服务注入到另一个服务中?

    假设我有这样的结构:

    AppBundle
        Service
            ServiceOne.php
            ServiceTwo.php
    

    my 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。

    我也清除了缓存。