Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/php/271.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Php 如何在Symfony中的另一个服务中注入服务?_Php_Symfony - Fatal编程技术网

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

Php 如何在Symfony中的另一个服务中注入服务?,php,symfony,Php,Symfony,我正在尝试在另一个服务中使用日志服务,以便对该服务进行故障排除 我的config.yml如下所示: services: userbundle_service: class: Main\UserBundle\Controller\UserBundleService arguments: [@security.context] log_handler: class: %monolog.handler.stream.cla

我正在尝试在另一个服务中使用日志服务,以便对该服务进行故障排除

我的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]] ]
这在控制器等方面效果很好。但是,当我在其他服务中使用它时,我不会感到不适


有什么提示吗?

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

假设您的其他服务是
userbundle\u服务

userbundle_service:
    class:        Main\UserBundle\Controller\UserBundleService
    arguments: [@security.context, @logger]
现在,如果您正确地更新了记录器,记录器将被传递给
UserBundleService
构造函数,例如

protected $securityContext;
protected $logger;

public function __construct(SecurityContextInterface $securityContext, Logger $logger)
{
    $this->securityContext = $securityContext;
    $this->logger = $logger;
}
对于Symfony 3.3、4.x及以上版本,最简单的解决方案是使用依赖项注入 您可以直接将服务注入到另一个服务中,(例如
MainService

然后简单地在MainService的任何方法中使用注入的服务

// AppBundle/Services/MainService.php
public function mainServiceMethod() {
    $this->injectedService->doSomething();
}
还有维奥拉!您可以访问注入服务的任何功能

对于Symfony的旧版本,其中不存在自动布线-
公共函数uu构造(SecurityContextInterface$securityContext){$this->securityContext=$securityContext;$this->logger=$logger;}构造函数中没有$logger参数。所以对于每个可注入服务,都必须以这种方式包含它?仅获取日志消息似乎需要大量工作。受保护的$securityContext;受保护的数据记录器;公共函数uu构造(SecurityContextInterface$securityContext,Logger$Logger){$this->securityContext=$securityContext;$this->Logger=$Logger;}在最新版本的Symfony中,服务名称周围必须有引号,如:
参数:['@security.context','@Logger']
对我来说效果很好。我尝试过这样做,以便两个服务可以相互引用,但最终会出现循环引用问题。
// AppBundle/Services/MainService.php
public function mainServiceMethod() {
    $this->injectedService->doSomething();
}
// services.yml
services:
    \AppBundle\Services\MainService:
        arguments: ['@injectedService']