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

时间:2015-02-09 23:02:06

标签: php symfony encapsulation

是否可以在实体类中获得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();
}

2 个答案:

答案 0 :(得分:2)

日期时间:

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

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

如果您有很多需要此实体的实体,您可以考虑使用Doctrine2侦听器来防止重复代码。

对于所有权属性:

如果您始终要将实体的所有权设置为“当前登录的用户”,则最好使用Doctrine2侦听器或订阅者。 这样,您就不必将此逻辑添加到控制器或任何需要创建实体的位置。

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

按照文档创建一个监听器服务,确保它使用构造函数获取安全性上下文。 将其设置为事件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);
            }
        }
    }
}

请注意,这不会检查用户是否确实已登录...

答案 1 :(得分:0)

确实这是错误的。

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

旁注我建议使用prePersist和preUpdate生命周期回调来处理实体时间戳。这个lib(php 5.4+)提供了非常简单的工具集来实现这些功能:https://github.com/KnpLabs/DoctrineBehaviors