如何在Symfony中的另一个服务中注入服务? [英] How to inject a service in another service in Symfony?
本文介绍了如何在Symfony中的另一个服务中注入服务?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正试图在另一个服务中使用日志记录服务,以便对该服务进行故障排除.
I am trying to use the logging service in another service in order to trouble shoot that service.
我的config.yml看起来像这样:
My config.yml looks like this:
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]] ]
这在控制器等中工作正常.但是,在其他服务中使用它时,我却没有表现出来.
This works fine in controllers etc. however I get no out put when I use it in other services.
有什么提示吗?
推荐答案
您将服务ID作为参数传递给服务的构造方法或设置方法.
You pass service id as argument to constructor or setter of a service.
假设您的其他服务是userbundle_service
:
userbundle_service:
class: Main\UserBundle\Controller\UserBundleService
arguments: [@security.context, @logger]
现在Logger传递给UserBundleService
构造函数,前提是您已正确更新它,例如.
Now Logger is passed to UserBundleService
constructor provided you properly update it, e.G.
protected $securityContext;
protected $logger;
public function __construct(SecurityContextInterface $securityContext, Logger $logger)
{
$this->securityContext = $securityContext;
$this->logger = $logger;
}
这篇关于如何在Symfony中的另一个服务中注入服务?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文