简体   繁体   English

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

[英]Symfony2 : get security.context inside entity class

Is it possible to get security.context inside an entity class? 是否可以在实体类中获取security.context

I know the following doesn't work. 我知道以下不起作用。 I don't know how to implement the $user part. 我不知道如何实现$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();
}

For datetimes: 对于日期时间:

For the timestamps you are probably best of using the @hasLifeCycleCallback annotation and some additional methods marked as @prePersist and @preUpdate. 对于时间戳,您可能最好使用@hasLifeCycleCallback注释和一些标记为@prePersist和@preUpdate的其他方法。 For created you could even just do it in the __constructor itself. 对于创建,您甚至可以在__constructor本身中执行此操作。

Note that you must use @preUpdate for the $updatedAt property, @prePersist is only for new entities. 请注意,必须将@preUpdate用于$ updatedAt属性,@prePersist仅用于新实体。

If you have a lot of entities that need this, you might consider a Doctrine2 listener to prevent repeated code. 如果你有很多需要它的实体,你可以考虑使用Doctrine2监听器来防止重复代码。

For ownership properties: 对于所有权属性:

If you always want to set the ownership of an entity to the "currently logged in user", you are probably best of using a Doctrine2 listener or subscriber. 如果您始终希望将实体的所有权设置为“当前登录的用户”,则最好使用Doctrine2侦听器或订阅者。 This way you don't have to add this logic to your controller, or wherever you need to create an entity. 这样,您无需将此逻辑添加到控制器或任何需要创建实体的位置。

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://symfony.com/doc/current/cookbook/doctrine/event_listeners_subscribers.html http://docs.doctrine-project.org/projects/doctrine-orm/en/latest/reference/events.html#onflush

Create a listener-service as documented, make sure it gets the security-context using the constructor. 按照文档创建一个监听器服务,确保它使用构造函数获取安全性上下文。 Set it to the event onFlush, this way you can adjust the entity just prior to actual saving. 将其设置为事件onFlush,这样您就可以在实际保存之前调整实体。 This is the best event to handle this kind of thing. 这是处理此类事情的最佳事件。

Make sure you follow the footnotes in the onFlush chapter on the Doctrine documentation, otherwise the last-minute-change won't be picked up by Doctrine. 请确保遵循Doctrine文档中onFlush章节中的脚注,否则Doctrine将不会收到最后一刻的更改。

Your listener should probably look something like: 你的听众应该看起来像:

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

Please note that this does not check if a user is actually logged in... 请注意,这不会检查用户是否确实已登录...

Indeed this is wrong. 确实这是错误的。

Keep it simple, you want to set the owner of your entity when creating it? 保持简单,您想在创建实体时设置实体的所有者吗? Pass it to your entity constructor and set it there. 将它传递给您的实体构造函数并将其设置在那里。

Side note I'd recommend using a prePersist and preUpdate lifecycle callback to handle entity timestamps. 附注我建议使用prePersist和preUpdate生命周期回调来处理实体时间戳。 This lib (php 5.4+) offers very easy set of tools to implement such features: https://github.com/KnpLabs/DoctrineBehaviors 这个lib(php 5.4+)提供了非常简单的工具来实现这些功能: https//github.com/KnpLabs/DoctrineBehaviors

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM