Symfony2:在实体类中获取security.context


Symfony2 : get security.context inside entity class

是否可以在实体类中获取security.context

我知道以下不起作用。我不知道如何实现$user部分。

/**
 * Set createdAt
 *
 * @ORM'PrePersist
 */
public function setCreatedAt()
{
    $user = $this->get('security.context')->getToken()->getUser();
    $this->owner = $user->getId();
    $this->createdAt = new 'DateTime();
    $this->updatedAt = new 'DateTime();
}

对于日期时间:

对于时间戳,您可能最好使用@hasLifeCycleCallback注释和一些标记为@prePersist和@preUpdate的其他方法。对于created,您甚至可以在__constructor本身中执行它。

请注意,$updatedAt属性必须使用@preUpdate,@prePersist仅用于新实体。

如果有很多实体需要这样做,那么可以考虑使用Doctrine2侦听器来防止代码重复。

对于所有权财产:

如果您总是想将实体的所有权设置为"当前登录的用户",那么最好使用Doctrine2侦听器或订阅者。这样,您就不必将此逻辑添加到控制器中,也不必在需要创建实体的任何位置添加此逻辑。

http://symfony.com/doc/current/cookbook/doctrine/event_listeners_subscribers.htmlhttp://docs.doctrine-project.org/projects/doctrine-orm/en/latest/reference/events.html#onflush

根据文档创建侦听器服务,确保它使用构造函数获取安全上下文。将其设置为onFlush事件,这样您就可以在实际保存之前调整实体。这是处理这种事情的最佳活动。

请确保遵循条令文件onFlush一章中的脚注,否则条令不会注意最后一分钟的更改。

你的听众可能应该看起来像:

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);
            }
        }
    }
}

请注意,这不会检查用户是否真的登录…

这确实是错误的。

保持简单,您想在创建实体时设置实体的所有者吗?将它传递给实体构造函数并在那里进行设置。

附带说明我建议使用prePersist和preUpdate生命周期回调来处理实体时间戳。这个lib(php5.4+)提供了一组非常简单的工具来实现这些功能:https://github.com/KnpLabs/DoctrineBehaviors