英文:
Same Doctrine ORM listener for multiple entitites
问题
我会快速回答。如果两个不同的实体都扩展了相同的EntityInterface接口,并且你的postPersist事件监听器的函数签名如下:
public function postPersist(EntityInterface $entity, LifecycleEventArgs $event = null)
那么你可以使用上面提供的XML配置使同一个监听器类响应两个不同的实体的postPersist事件。在XML配置中,你为每个实体添加了相应的标签,如下所示:
<service id="app.entity.my_listener"
         class="App\Entity\MyListener" lazy="true">
    <tag name="doctrine.orm.entity_listener" entity="App\Entity\Entity1" event="postPersist"/>
    <tag name="doctrine.orm.entity_listener" entity="App\Entity\Entity2" event="postPersist"/>
    <tag name="kernel.event_subscriber" />
</service>
这样配置后,你的MyListener类将能够响应Entity1和Entity2两个实体的postPersist事件,因为它们都实现了EntityInterface接口。
英文:
So I will be quick. Let's say you have a postPersist event. Can you make the same listener class respond to two different entities if they extend same interface?
        <service id="app.entity.my_listener"
                 class="App\Entity\MyListener" lazy="true">
            <tag name="doctrine.orm.entity_listener" entity="App\Entity\Entity1" event="postPersist"/>
            <tag name="doctrine.orm.entity_listener" entity="App\Entity\Entity2" event="postPersist"/>
            <tag name="kernel.event_subscriber" />
        </service>
Keep in mind, both entities extend the same EntityInterface so my function signature takes:
    public function postPersist(EntityInterface $entity, LifecycleEventArgs $event = null)
For "reasons" I can not validate this myself, but wondered if someone else is able to give an answer?
答案1
得分: 1
如果您使用Doctrine生命周期监听器:https://symfony.com/doc/current/doctrine/events.html#doctrine-lifecycle-listeners
您可以使您的情况工作。因为在这种情况下,它们不会在特定实体上触发。这由您决定。
因此,如果监听器只应响应特定接口,正如@Bossman在他的评论中所说,您可以这样做:
public function postPersist(LifecycleEventArgs $args): void
{
    $entity = $args->getObject();
    // 如果此监听器仅适用于某些实体类型,
    // 请尽早添加一些代码来检查实体类型
    if (!$entity instanceof EntityInterface) {
        return;
    }
    $entityManager = $args->getObjectManager();
    // ... 使用Product实体进行一些操作
}
希望这能帮助您。
英文:
If you use doctrine lifecycle listener :
https://symfony.com/doc/current/doctrine/events.html#doctrine-lifecycle-listeners
You can make your case work. Since in this case they do not trigger on a specific entity. It is on your hand.
So if the listener should respond to only a specific interface.
As @Bossman said in his comment, you can do :
 public function postPersist(LifecycleEventArgs $args): void
{
    $entity = $args->getObject();
    // if this listener only applies to certain entity types,
    // add some code to check the entity type as early as possible
    if (!$entity instanceof EntityInterface) {
        return;
    }
    $entityManager = $args->getObjectManager();
    // ... do something with the Product entity
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。


评论