我正在尝试在另一个服务中使用日志记录服务,以便对该服务进行故障排除。
我的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]] ]这在控制器等中工作得很好,但是当我在其他服务中使用它时却得不到输出。
有什么建议吗?
发布于 2012-08-04 02:50:34
将服务id作为参数传递给服务的构造器或设置器。
假设您的另一个服务是userbundle_service
userbundle_service:
class: Main\UserBundle\Controller\UserBundleService
arguments: [@security.context, @logger]现在Logger被传递给UserBundleService构造函数,只要你正确地更新它,例如。
protected $securityContext;
protected $logger;
public function __construct(SecurityContextInterface $securityContext, Logger $logger)
{
$this->securityContext = $securityContext;
$this->logger = $logger;
}发布于 2017-08-30 20:07:31
对于Symfony 3.3、4.x、5.x及更高版本,最简单的解决方案是使用依赖注入
您可以直接将服务注入到另一个服务中(比如MainService)
// AppBundle/Services/MainService.php
// 'serviceName' is the service we want to inject
public function __construct(\AppBundle\Services\serviceName $injectedService) {
$this->injectedService = $injectedService;
}然后,简单地在MainService的任何方法中使用注入的服务
// AppBundle/Services/MainService.php
public function mainServiceMethod() {
$this->injectedService->doSomething();
}还有中提琴!您可以访问注入服务的任何功能!
对于不存在自动装配的Symfony的旧版本-
// services.yml
services:
\AppBundle\Services\MainService:
arguments: ['@injectedService']发布于 2021-11-08 14:08:19
更通用的选择是,只需为您想要注入的类创建一个特征。例如:
特征/SomeServiceTrait.php
Trait SomeServiceTrait
{
protected SomeService $someService;
/**
* @param SomeService $someService
* @required
*/
public function setSomeService(SomeService $someService): void
{
$this->someService = $someService;
}
}以及你需要一些服务的地方:
class AnyClassThatNeedsSomeService
{
use SomeServiceTrait;
public function getSomethingFromSomeService()
{
return $this->someService->something();
}
}由于@required注释,类将自动加载。当您想要将服务注入到许多类(如事件处理程序)中时,这通常会使它的实现速度更快。
https://stackoverflow.com/questions/11801541
复制相似问题