且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

对具有不同服务参数的多个实体使用相同的EntityListener

更新时间:2023-02-11 13:24:12

您可以使用 @configured_service_id 表示法将其他服务注入到服务中.此方法适用于构造函数参数和setter注入.

You can inject other services into services with the @configured_service_id notation.This works for constructor arguments and setter injection.

通常所说:不要尝试在不需要的地方找到抽象.在大多数情况下,从长远来看,稍微重复一些代码就容易得多.

Generally spoken: Do not try to find an abstraction where it isn't needed. Most of the time a little code duplication is far easier in long term.

我将为每个目的简单地构建两个独立的侦听器.

I would simply built two independent listeners for each purpose.

做一个简单的检查,如果Entity不是应由同一侦听器处理的两个实体之一,则跳出处理程序:

Do a simple check that jumps out of the handler if the Entity is NOT one of the two Entities that should be handled with the same listener:

<?php
use Doctrine\Common\Persistence\Event\LifecycleEventArgs;

class MyEventListener
{
    public function preUpdate(LifecycleEventArgs $args)
    {
        $entity = $args->getObject();
        $entityManager = $args->getObjectManager();

        if (!$entity instanceof EntityA && !$entity instanceof EntityB) {
            return;
        }

        /* Your listener code */
    }
}