如何在 symfony 4 中公开 LoggerInterface 服务 [英] How to make LoggerInterface service public in symfony 4

查看:21
本文介绍了如何在 symfony 4 中公开 LoggerInterface 服务的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在 symfony 中公开 Psr\Log\LoggerInterface 以便能够直接从容器中使用 $container->get('Psr\Log\LoggerInterface').

I want to have Psr\Log\LoggerInterface public in symfony to be able to get it directly from the container with $container->get('Psr\Log\LoggerInterface').

我尝试了以下 services.yaml:

_defaults:
 public: true

Psr\Log\LoggerInterface:
 public: true

Psr\Log\LoggerInterface:
 alias: 'logger'
 public: true

Psr\Log\LoggerInterface:
 alias: 'monolog.logger'
 public: true

我不知道为什么重写服务这么难.

I can not get a clue why it is so hard to rewrite a service.

推荐答案

如前所述,不鼓励直接从容器访问服务.但我有点好奇如何将私人服务公开.我尝试了问题中列出的内容并确认它不起作用.

As previously noted, directly accessing services from the container is discouraged. But I was a bit curious to see how to make a private service public. I tried what was listed in the question and confirmed it did not work.

这可能不是最简单的方法,但编译器传递可以解决问题:

This may not be the simplest approach but a compiler pass will do the trick:

# src/Kernel.php
# Make the kernel a compiler pass
use Psr\Log\LoggerInterface;
use Symfony\Component\DependencyInjection\Compiler\CompilerPassInterface;
class Kernel extends BaseKernel implements CompilerPassInterface
...
public function process(ContainerBuilder $container)
{
    $logger = $container->getAlias(LoggerInterface::class);
    $logger->setPublic(true);
}

# And that should do the trick, you can confirm with
bin/console debug:container Psr\Log\LoggerInterface

请注意,只有注入了完整容器的服务才能利用这一点.从 AbstractController 扩展而来的控制器只能访问少量服务.

Be aware that only services which have the complete container injected will be able to take advantage of this. Controllers which extend from AbstractController only have access to a small number of services.

如果需要,请查看服务订阅者控制器中的记录器,或者如果您只是想要一种更好"的方式来做到这一点.

Take a look at Service Subscribers if you need the logger in your controller or if you just want a "better" way of doing this.

这篇关于如何在 symfony 4 中公开 LoggerInterface 服务的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆