我最近从 Symfony 3.4 升级到 4.4
代码库非常大,并且有很多container->get('logger')来自各地的引用。
我一直试图公开这项服务,但我找不到任何例子。错误:
编译容器时,“logger”服务或别名已被删除或内联。您应该将其公开,或者停止直接使用容器并使用依赖项注入。
在我的service.yml尝试中,我没有运气:
Psr\Log\LoggerInterface:
public: true
Psr\Log\LoggerInterface:
alias: 'logger'
public: true
Psr\Log\LoggerInterface:
alias: 'monolog.logger'
public: true
Run Code Online (Sandbox Code Playgroud)
我怎样才能公开该logger服务?
注意:在从 3.4->4.4 的升级中,我们没有更新代码库以使用 Symfony Flex
您可以使用Compiler Pass来完成此操作。(文档适用于 4.4,因为这是您正在使用的版本,当前文档位于此处)。
更改您的应用程序Kernel,使其实现CompilerPassInterface,并且在process()方法上您可以直接操作服务容器:
// src/Kernel.php
namespace App;
use Symfony\Bundle\FrameworkBundle\Kernel\MicroKernelTrait;
use Symfony\Component\DependencyInjection\Compiler\CompilerPassInterface;
use Symfony\Component\DependencyInjection\ContainerBuilder;
use Symfony\Component\HttpKernel\Kernel as BaseKernel;
class Kernel extends BaseKernel implements CompilerPassInterface
{
use MicroKernelTrait;
// ...
public function process(ContainerBuilder $container): void
{
$container->getDefinition('monolog.logger')->setPublic(true);
}
}
Run Code Online (Sandbox Code Playgroud)
无论如何,如果我是你,我会研究使用Rector之类的东西来自动更新你的代码。它甚至包括针对此特定用例的规则,将注入容器和公共服务的(滥用)使用转换为正确的依赖项注入。