如何在 Symfony 中从编译器传递注入共享服务

2024-01-12

我正在尝试通过旨在替换 FOSRestBundle 中的服务之一的编译器通道注入令牌存储服务:

<?php

namespace App\Compiler;

use App\Event\Listener\RestParamConverter;
use Symfony\Component\DependencyInjection\Compiler\CompilerPassInterface;
use Symfony\Component\DependencyInjection\ContainerBuilder;

class RestParamConverterOverride implements CompilerPassInterface
{
    /**
     * You can modify the container here before it is dumped to PHP code.
     *
     * @param ContainerBuilder $container
     */
    public function process(ContainerBuilder $container)
    {
        $definition = $container->getDefinition('fos_rest.converter.request_body');
        $definition->setClass(RestParamConverter::class);
        $definition->addArgument($container->getDefinition('security.token_storage'));
    }
}

由于某种原因,即使安全系统正确设置了令牌TokenStorage,在我的自定义服务中,当我访问TokenStorage, $tokenStorage->getToken()似乎回来了null。我已经调试了代码,并确保在尝试检索该值之前身份验证正在运行。

我已经使用其他服务进行了测试,并且我看到了我注入的任何内容的行为$definition->addArgument($container->getDefinition(SERVICE_HERE));。这很奇怪,但在编译器传递中,它似乎创建了该服务的新实例,而不是使用共享服务。

在其他部分,服务注入工作正常 - 只是在这些编译器通道中不工作。谁能解释一下为什么会这样?


该文档展示了如何注入对现有服务的引用,而不是创建该服务的新实例:https://symfony.com/doc/current/components/dependency_injection.html#basic-usage https://symfony.com/doc/current/components/dependency_injection.html#basic-usage

具体来说,使用:

$definition->addArgument(new Reference('service_name'))
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

如何在 Symfony 中从编译器传递注入共享服务 的相关文章

随机推荐