无法在编译过程中添加学说订阅者标签

Unable to add a doctrine subcriber tag in compilation pass

我有一个简单的订阅者,如下所示:

namespace App;

use Doctrine\Common\EventSubscriber;
use Doctrine\ORM\Event\OnFlushEventArgs;
use Doctrine\ORM\Events;

class TestSubscriber implements EventSubscriber
{
    public function getSubscribedEvents(): array
    {
        return [
            Events::onFlush,
        ];
    }

    public function onFlush(OnFlushEventArgs $eventArgs): void
    {
        // Some stuff
    }
}

当我在编译过程中添加 Doctrine 订阅者标签时,onFlush 方法永远不会被触发:

namespace App\DepencyInjection\Compiler;

use App\TestSubscriber;

use Symfony\Component\DependencyInjection\Compiler\CompilerPassInterface;
use Symfony\Component\DependencyInjection\ContainerBuilder;
use Symfony\Component\DependencyInjection\Definition;

class TestSubscriberPass implements CompilerPassInterface
{
    public function process(ContainerBuilder $container)
    {
        $definition = new Definition(TestSubscriber::class);
        $definition->addTag('doctrine.event_subscriber');
        $container->setDefinition('app.test_subscriber', $definition);
    }
}

但是如果我在 services.yaml 中声明标签,它会很好地工作:

services:
    app.test_subscriber:
        class: App\TestSubscriber
        tags:
            - { name: 'doctrine.event_subscriber' }

我错过了什么?编译过程执行成功,但标签似乎被忽略了。即使我禁用 TestSubscriber class.

的自动装配,也会出现此问题

这是 debug:container 命令的输出:

我终于找到了解决办法: compilation pass必须在Doctrine编译之前执行,所以我在Kernel.php:

的compilation pass declaration中设置了一个优先级grower than 0
final class Kernel extends BaseKernel
{
    use MicroKernelTrait;
    
    protected function build(ContainerBuilder $container): void
    {
        $container->addCompilerPass(new TestSubscriberPass(), PassConfig::TYPE_BEFORE_OPTIMIZATION, 100);
    }
}