我如何添加多个事件在services.yml文件作为事件侦听器在学说symfony

7fhtutme  于 2023-10-23  发布在  其他
关注(0)|答案(3)|浏览(82)

我用这个:

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

现在如果我试着听两个这样的事件:

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

它给出一个错误。

7gcisfzg

7gcisfzg1#

我认为你可以这样做:

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

zpqajqem2#

你需要一个事件订阅者而不是一个事件监听器。
你可以将service标签改为doctrine.event_subscriber,你的类应该实现Doctrine\Common\EventSubscriber。你需要定义一个getSubscribedEvents来满足EventSubscriber,它返回一个你想要订阅的事件数组。
ex

<?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)
    {

    }
}
cgvd09ve

cgvd09ve3#

从Symfony 6.3开始,不推荐使用订阅服务器。因此,您可以使用以下内容:

Acme\SearchBundle\Listener\SearchIndexer:
        tags:
            -
                {
                  name: 'doctrine.event_listener',
                
                  # this is the only required option for the lifecycle listener tag
                  event: '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: 'postUpdate',
                  
                  # 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'
                }

相关问题