Loggable 侦听器仅保存实体的受监视属性随时间的变化值。
它不会触发事件,它会监听onFlush
and postPersist
教义事件。
我认为您正在寻找 preUpdate 和 prePersist 事件的 Doctrine 侦听器,您可以在其中操作更改集flush
.
see: http://doctrine-orm.readthedocs.org/en/latest/reference/events.html http://doctrine-orm.readthedocs.org/en/latest/reference/events.html
如果您使用的是 Doctrine 2.4+,您可以轻松地将它们添加到您的实体中:
简单实体类:
namespace Your\Namespace\Entity;
use Doctrine\ORM\Mapping as ORM;
/**
* @ORM\Entity
* @ORM\EntityListeners({"Your\Namespace\Listener\DogListener"})
*/
class Dog
{
/**
* @ORM\Id
* @ORM\GeneratedValue(strategy="IDENTITY")
* @ORM\Column(type="integer")
*/
private $id;
/**
* @ORM\Column(type="string", length=100)
*/
private $name;
/**
* @ORM\Column(type="integer")
*/
private $age;
/**
* @return int
*/
public function getId()
{
return $this->id;
}
/**
* @param int $id
*/
public function setId($id)
{
$this->id = $id;
}
/**
* @return string
*/
public function getName()
{
return $this->name;
}
/**
* @param string $name
*/
public function setName($name)
{
$this->name = $name;
}
/**
* @return int
*/
public function getAge()
{
return $this->age;
}
/**
* @param int $age
*/
public function setAge($age)
{
$this->age = $age;
}
}
Then in Your\Namespace\Listener
您创建 ListenerClassDogListener
:
namespace Your\Namespace\Listener;
use Doctrine\ORM\Event\LifecycleEventArgs;
use Doctrine\ORM\Event\PreUpdateEventArgs;
use Your\Namespace\Entity\Dog;
class DogListener
{
public function preUpdate(Dog $dog, PreUpdateEventArgs $event)
{
if ($event->hasChangedField('name')) {
$updatedName = $event->getNewValue('name'). ' the dog';
$dog->setName($updatedName);
}
if ($event->hasChangedField('age')) {
$updatedAge = $event->getNewValue('age') % 2;
$dog->setAge($updatedAge);
}
}
public function prePersist(Dog $dog, LifecycleEventArgs $event)
{
//
}
}
清除缓存,刷新时应调用监听器。
Update
您对 recomputeSingleEntityChangeSet 的看法是正确的,在本例中不需要它。我更新了监听器的代码。
第一个选择(实体内方法)的问题是您无法在该方法中注入其他服务。
如果您只需要 EntityManager,那么是的,这是最简单的代码方式。
通过外部 Listener 类,您可以做到这一点。
如果这 1000 个字段位于多个单独的实体中,则第二种类型的侦听器将是最合适的。你可以创建一个NotifyOnXUpdateListener
这将包含您所有的手表/通知逻辑。
Update 2
要在 EntityListener 中注入服务,请将侦听器声明为标记为的服务doctrine.orm.entity_listener
并注入你需要的东西。
<service id="app.entity_listener.your_service" class="Your\Namespace\Listener\SomeEntityListener">
<argument type="service" id="logger" />
<argument type="service" id="event_dispatcher" />
<tag name="doctrine.orm.entity_listener" />
</service>
听众将如下所示:
class SomeEntityListener
{
private $logger;
private $dispatcher;
public function __construct(LoggerInterface $logger, EventDispatcherInterface $dispatcher)
{
$this->logger = $logger;
$this->dispatcher = $dispatcher;
}
public function preUpdate(Block $block, PreUpdateEventArgs $event)
{
//
}
}
根据:如何在 Symfony 2.4 中使用 Doctrine 实体监听器? https://stackoverflow.com/questions/22114239/how-to-use-doctrine-entity-listener-with-symfony-2-4它需要 DoctrineBundle 1.3+