Symfony 3 - 如何将当前登录的用户设置为实体 "author"

Symfony 3 - How to set currently logged user as entity "author"

假设我有两个实体 classes:
\AppBundle\Entity\User - 用户提供商;
\AppBundle\Entity\Article - 简单的文章。

Article class 也有这些属性:
author - 指示创建此特定实体的用户;
updatedBy - 指示用户最近更新了特定文章的内容。

如何将当前登录的用户对象传递给 Article 实体以在 author and/or updatedBy 后端属性上设置特定值 EasyAdminBundle Symfony 3.0.1?

如果您与作者实体有关系

 $em = $this->getDoctrine()->getManager();
$user = new User();
$user->setAuthor($this->getUser());
$em->persist($user);
$em->flush();

在控制器上,但这是个坏主意。使用命令或其他设计模式。

如果你在控制器中,你就这样做

$article->setAuthor($this->getUser());
$article->setUpdatedBy($this->getUser());

如果你希望这是自动的

您需要在 Doctrine 事件上声明一个侦听器。在你的情况下,我猜想在 preUpdate 中包含当前用户。

这里有一个非常好的文档http://symfony.com/doc/current/cookbook/doctrine/event_listeners_subscribers.html

我在这里编辑以回答您的评论

不用担心,当您将侦听器声明为服务时,您可以注入用户实体

例如:

services:
    your_listener:
        class:     App\AppBundle\Your_Listener
        arguments: ["@security.token_storage"]

您的听众:

private $current_user;

public function __construct($security_context) {
        if ($security_context->getToken() != null) {
            $this->current_user = $security_context->getToken()->getUser();
        }
    } 

现在你可以

$entity= $args->getEntity(); // get your Article

if (!$entity instanceof Article) {
        return;
}

$entity->setAuthor($this->current_user);
$entity->setUpdatedBy($this->current_user);