对于日期时间:
对于时间戳,您可能最好使用 @hasLifeCycleCallback 注释和一些标记为 @prePersist 和 @preUpdate 的附加方法。
对于创建的,你甚至可以在 __constructor 本身中完成它。
请注意,您必须对 $updatedAt 属性使用 @preUpdate,@prePersist 仅适用于新实体。
如果您有很多实体需要此功能,您可以考虑使用 Doctrine2 侦听器来防止重复代码。
对于所有权财产:
如果您始终希望将实体的所有权设置为“当前登录的用户”,那么您最好使用 Doctrine2 侦听器或订阅者。
这样,您就不必将此逻辑添加到控制器或任何需要创建实体的地方。
http://symfony.com/doc/current/cookbook/doctrine/event_listeners_subscribers.html http://symfony.com/doc/current/cookbook/doctrine/event_listeners_subscribers.html
http://docs.doctrine-project.org/projects/doctrine-orm/en/latest/reference/events.html#onflush http://docs.doctrine-project.org/projects/doctrine-orm/en/latest/reference/events.html#onflush
按照文档创建侦听器服务,确保它使用构造函数获取安全上下文。
将其设置为 onFlush 事件,这样您就可以在实际保存之前调整实体。这是处理此类事情的最佳事件。
确保遵循 Doctrine 文档 onFlush 章节中的脚注,否则 Doctrine 将不会接收最后一刻的更改。
你的听众可能看起来像这样:
class FlushExampleListener
{
public function onFlush(OnFlushEventArgs $eventArgs)
{
$em = $eventArgs->getEntityManager();
$uow = $em->getUnitOfWork();
foreach ($uow->getScheduledEntityInsertions() as $entity) {
if ($entity instanceof YourClass) {
// change owner
$entity->setOwner($this->securityContext->getToken()->getUser());
// tell doctrine you changed it
$uow->recomputeSingleEntityChangeSet($em->getClassMetadata(get_class($entity)), $entity);
}
}
foreach ($uow->getScheduledEntityUpdates() as $entity) {
if ($entity instanceof YourClass) {
// change owner
$entity->setOwner($this->securityContext->getToken()->getUser());
// tell doctrine you changed it
$uow->recomputeSingleEntityChangeSet($em->getClassMetadata(get_class($entity)), $entity);
}
}
}
}
请注意,这不会检查用户是否实际登录......