如何在 services.yml 文件中添加多个事件作为 Doctrine symfony 中的事件监听器

问题描述 投票:0回答:3

我正在用这个:

my.listener:
        class: Acme\SearchBundle\Listener\SearchIndexer
        tags:
            - { name: doctrine.event_listener, event: postPersist }

现在,如果我尝试监听两个这样的事件:

- { name: doctrine.event_listener, event: postPersist, preUpdate }

它给出了一个错误。

php symfony doctrine
3个回答
24
投票

我认为你可以这样做:

my.listener:
        class: Acme\SearchBundle\Listener\SearchIndexer
        tags:
            - { name: doctrine.event_listener, event: postPersist }
            - { name: doctrine.event_listener, event: preUpdate }

7
投票

您需要一个事件订阅者而不是事件监听器。

您可以将服务标签更改为

doctrine.event_subscriber
,并且您的类应该实现
Doctrine\Common\EventSubscriber
。您需要定义一个
getSubscribedEvents
来满足
EventSubscriber
,它返回您想要订阅的事件数组。

<?php

namespace Company\YourBundle\Listener;

use Doctrine\Common\EventArgs;
use Doctrine\Common\EventSubscriber;

class YourListener implements EventSubscriber
{
    public function getSubscribedEvents()
    {
        return array('prePersist', 'onFlush');
    }

    public function prePersist(EventArgs $args)
    {

    }

    public function onFlush(EventArgs $args)
    {

    }
}

0
投票

从 Symfony 6.3 开始,生命周期订阅者已被弃用。 所以你可以使用这个: Acme\SearchBundle\Listener\SearchIndexer: 标签: - {name: 'doctrine.event_listener', # 这是生命周期监听器标签唯一必需的选项 事件:'postPersist',

            # listeners can define their priority in case multiple subscribers or listeners are associated
            # to the same event (default priority = 0; higher numbers = listener is run earlier)
            priority: 500,

            # you can also restrict listeners to a specific Doctrine connection
            connection: 'default'}
            
        -   {name: 'doctrine.event_listener',
            # this is the only required option for the lifecycle listener tag
            event: 'preUpdate',

            # listeners can define their priority in case multiple subscribers or listeners are associated
            # to the same event (default priority = 0; higher numbers = listener is run earlier)
            priority: 500,

            # you can also restrict listeners to a specific Doctrine connection
            connection: 'default'}
© www.soinside.com 2019 - 2024. All rights reserved.