您可以使用 Doctrine preUpdate 事件侦听器来执行此操作。这是一个将更改发送到记录器的简单示例:
use Psr\Log\LoggerInterface as Logger;
use Doctrine\ORM\Event\PreUpdateEventArgs;
class ChangeLoggerListener
{
protected $logger;
public function __construct(Logger $logger)
{
$this->logger = $logger;
}
public function preUpdate(PreUpdateEventArgs $eventArgs)
{
//find out class and id of object being updated
$obj=$eventArgs->getEntity();
$class=get_class($eventArgs->getEntity());
$id=$obj->getId();
$log="$class($id) updated: ";
//find out what has changed...
$changes=$eventArgs->getEntityChangeSet();
$separator='';
foreach ($changes as $field => $values) {
$log.=$separator."$field changed from {$values[0]} to {$values[1]}";
$separator=", ";
}
//send it to logger
$this->logger->info($log);
}
}
手册页显示了如何注册监听器,但如果你使用 Symfony,你可以在 services.yml 中将监听器注册为服务
my.change_logger:
class: My\ExampleBundle\Listener\ChangeLoggerListener
arguments: [@logger]
tags:
- { name: doctrine.event_listener, event: preUpdate }