如何在Symfony的另一个服务中注入服务?

jin*_*ini 25 php symfony

我试图在另一个服务中使用日志记录服务,以便解决该服务的麻烦.

我的config.yml看起来像这样:

services:
    userbundle_service:
        class:        Main\UserBundle\Controller\UserBundleService
        arguments: [@security.context]

    log_handler:
        class: %monolog.handler.stream.class%
        arguments: [ %kernel.logs_dir%/%kernel.environment%.jini.log ]


    logger:
        class: %monolog.logger.class%
        arguments: [ jini ]
        calls: [ [pushHandler, [@log_handler]] ]
Run Code Online (Sandbox Code Playgroud)

这在控制器等中运行良好.但是当我在其他服务中使用它时,我没有得到任何结果.

有小费吗?

Ino*_*ryy 35

您将服务id作为参数传递给服务的构造函数或setter.

假设您的其他服务是userbundle_service:

userbundle_service:
    class:        Main\UserBundle\Controller\UserBundleService
    arguments: [@security.context, @logger]
Run Code Online (Sandbox Code Playgroud)

现在Logger被传递给UserBundleService构造函数,只要你正确地更新它,eG

protected $securityContext;
protected $logger;

public function __construct(SecurityContextInterface $securityContext, Logger $logger)
{
    $this->securityContext = $securityContext;
    $this->logger = $logger;
}
Run Code Online (Sandbox Code Playgroud)

  • 受保护的 $securityContext; 受保护的 $logger; 公共函数 __construct(SecurityContextInterface $securityContext, Logger $logger ) { $this->securityContext = $securityContext; $this->logger = $logger; } (3认同)
  • 那么对于每种注射服务,它都必须以这种方式包含在内?看起来只是获取日志消息的大量工作. (2认同)
  • 在最新版本的Symfony中,必须引用服务名称,如:`arguments:['@ security.context','@ logger']` (2认同)

Nik*_*hak 5

对于Symfony 3.3及更高版本,最简单的解决方案是使用依赖注入

您可以将服务直接注入到另一个服务中(例如MainService

// AppBundle/Services/MainService.php
// 'serviceName' is the service we want to inject
public function __construct(\AppBundle\Services\serviceName $injectedService)  {
    $this->injectedService = $injectedService;
}
Run Code Online (Sandbox Code Playgroud)

然后,只需在MainService的任何方法中使用注入的服务即可:

// AppBundle/Services/MainService.php
public function mainServiceMethod() {
    $this->injectedService->doSomething();
}
Run Code Online (Sandbox Code Playgroud)

和中提琴!您可以访问注入服务的任何功能!

对于不存在自动装配的Symfony的较旧版本-

// services.yml
services:
    \AppBundle\Services\MainService:
        arguments: ['@injectedService']
Run Code Online (Sandbox Code Playgroud)

  • 我已经尝试过这样做,以便两个服务可以相互引用,但最终会遇到循环引用问题。 (2认同)