跳到内容

实体监听器

编辑此页

作为服务的实体监听器必须在实体监听器解析器中注册。除了实体类中的注解/属性之外,你还需要使用 doctrine.orm.entity_listener 标记服务,以便它能够自动添加到解析器中。使用(可选的)entity_manager 属性来指定它应该注册到哪个实体管理器。

完整示例

1
2
3
4
5
6
7
8
9
10
11
12
13
14
<?php
// User.php

use Doctrine\ORM\Mapping as ORM;
use App\UserListener;

/**
 * @ORM\Entity
 * @ORM\EntityListeners({UserListener::class})
 */
class User
{
    // ....
}
1
2
3
4
5
6
7
services:
    App\UserListener:
        tags:
            # Minimal configuration below
            - { name: doctrine.orm.entity_listener }
            # Or, optionally, you can give the entity manager name as below
            #- { name: doctrine.orm.entity_listener, entity_manager: custom }

从 doctrine/orm 2.5 和 Doctrine bundle 1.5.2 开始,除了在实体上注册实体监听器,你也可以从服务定义中声明所有选项

1
2
3
4
5
6
7
8
9
10
11
services:
    App\UserListener:
        tags:
            -
                name: doctrine.orm.entity_listener
                event: preUpdate
                entity: App\Entity\User
                # entity_manager attribute is optional
                entity_manager: custom
                # method attribute is optional
                method: validateEmail

如果实体监听器没有在实体上注册,则 event 属性是必需的。 如果你没有指定 method 属性,它将回退到订阅的事件名称。

从 Doctrine bundle 1.12 开始,如果此方法不存在,但你的实体监听器是可调用的,它将回退到 __invoke() 方法。

另请参阅 https://www.doctrine-project.org/projects/doctrine-orm/en/latest/reference/events.html#entity-listeners 以获取关于实体监听器和 Symfony 所需的解析器的更多信息。

惰性实体监听器

你可以在标签上使用 lazy 属性,以确保监听器服务仅在实际使用时才会被实例化。

1
2
3
4
services:
    App\UserListener:
        tags:
            - { name: doctrine.orm.entity_listener, lazy: true }
本作品,包括代码示例,根据 Creative Commons BY-SA 3.0 许可协议发布。
目录
    版本