Symfony 3.4。无法覆盖服务。

4

我正在尝试覆盖“vendor”部分的某些服务。遵循这个指南https://symfony.com/doc/3.4/bundles/override.html,我编写了以下代码:

namespace AppBundle\DependencyInjection\Compiler;

use AppBundle\Service\Subscriber;
use Symfony\Component\DependencyInjection\Compiler\CompilerPassInterface;
use Symfony\Component\DependencyInjection\ContainerBuilder;

class OverrideServiceCompilerPass implements CompilerPassInterface
{
    public function process(ContainerBuilder $container)
    {
        $definition = $container->getDefinition('MyOldService');
        $definition->setClass(Subscriber::class); //my new service class
    }
}

在我创建了一个名为“AppBundle\Service\Subscriber”的订阅者类并尝试覆盖动作后:

<?php

namespace AppBundle\Service;

class Subscriber
{
   public function the_same_name_of_function_from_vendor()
   {
       dump('I am a new function!');die;
       return new Response('ok');
   }
}

但是什么也没有发生,Symfony继续从“vendor”部分调用函数。

我该如何正确地覆盖这个函数?


您是否确认您有正确的服务 ID 来进行覆盖? - JacobW
尝试在setclass之后转储$definition以查看其中的内容。 - Eakethet
2个回答

4
你需要在src/AppBundle/AppBundle.php文件中添加如下代码:
在build()函数中:
$container->addCompilerPass(new OverrideServiceCompilerPass());

所有类:

class AppBundle extends Bundle
{
    public function build(ContainerBuilder $container)
    {
        parent::build($container);

        $container->addCompilerPass(new OverrideServiceCompilerPass());
    }
}

https://symfony.com/doc/3.4/service_container/compiler_passes.html

否则你的编译器通道将无法加载。


2

对于覆盖服务特定情况,您只需要在您的Bundle(或app文件夹)services.yml中定义一个新服务即可:

       lexik_jwt_authentication.security.guard.jwt_token_authenticator:
       class: SeguridadBundle\DependencyInjection\MyJWTTokenAuthenticator
       arguments: ["@lexik_jwt_authentication.jwt_manager", "@event_dispatcher", "@lexik_jwt_authentication.extractor.chain_extractor"]

当然,有一些规则需要遵守:
  • 服务的名称必须与供应商中的名称完全相同。因此,我上面写的那个将覆盖LexikJWTAuthentication供应商中另一个名为lexik_jwt_authentication.security.guard.jwt_token_authenticator的服务。
  • 指定的类将是您自己实现的类。
因此,在覆盖服务时,您需要创建一个新的定义,保持与原始名称相同,但使用不同的类进行实例化。 请注意,出于兼容性考虑,建议按照与原始服务相同的接口实现相同的接口,即:遵循相同的约定以保证兼容性。
抱歉我的英语不好,希望这可以帮到你。

使用服务“key”语法(my.very.own.service.)对我很有帮助。最近我遵循了官方文档,但效果不是很好。 - chringel21

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接