对具有不同服务参数的多个实体使用相同的EntityListener [英] Using the same EntityListener for multiple entities with differrent service argument
问题描述
由于EntityListener被注册为服务,是否可以使用不同的参数多次注册相同的类,并将每个类与特定的实体相关联?
As an EntityListener is registered as a service, is it possible to register the same class multiple times with different argument and associate each of them with a particular entity ?
考虑以下实体:
/**
* Class EntityA
* @ORM\Entity
* @ORM\EntityListeners({"myBundle\EventListener\SharedListener"})
*/
class EntityA implements sharedBehaviourInterface
{
// stuff here
}
/**
* Class EntityB
* @ORM\Entity
* @ORM\EntityListeners({"myBundle\EventListener\SharedListener"})
*/
class EntityB implements sharedBehaviourInterface
{
// stuff here
}
我想为这两个先前的实体注册以下侦听器:
I would like to register the following listener for both previous entities as this :
class SharedListener
{
private $usefulParameter;
public function __construct($usefulParameter)
{
$this->usefulParameter = $usefulParameter;
}
/**
* @PrePersist
*
*/
public function prePersist(sharedBehaviourInterface $dbFile, LifecycleEventArgs $event)
{
// code here
}
// more methods
}
使用:
mybundle.entitya.listener:
class: myBundle\EventListener\SharedListener
arguments:
- '%entitya.parameter%' # The important change goes here ...
tags:
- { name: doctrine.orm.entity_listener }
mybundle.entityb.listener:
class: myBundle\EventListener\SharedListener
arguments:
- '%entityb.parameter%' # ... and here
tags:
- { name: doctrine.orm.entity_listener }
它不起作用,实际上让我感到惊讶的是,实体中的EntityListener声明针对的是Listener类而不是服务.是否可以针对特定服务?喜欢:
It does not work, and I'm actually surprised that the EntityListener declaration in the Entity targets the Listener class and not the service. Is it possible to target a specific service instead ? Like :
@ORM\EntityListeners({"mybundle.entityb.listener"})
或者我想做的事甚至不可能吗?
Or what I'm trying to do isn't even possible ?
推荐答案
您可以使用 @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 */
}
}
这篇关于对具有不同服务参数的多个实体使用相同的EntityListener的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!