Symfony 从实体获取连接的用户 ID

Al *_* ѫ 1 php symfony doctrine-orm

在 Symfony2.8/Doctrine2 应用程序中,我需要在 SQL 表的每一行中存储创建或更新该行的用户的 id(用户可以使用 Ldap 连接)。

因此,我的所有实体都继承了GenericEntity包含此变量的 a (如果我想存储 Ldap 用户名,类型将为字符串):

/**
 * @var integer
 *
 * @ORM\Column(name="zzCreationId", type="string", nullable=false)
 */
private $creationId;
Run Code Online (Sandbox Code Playgroud)

我使用prePersistCallback()自动分配这个值:

/**
 * @ORM\PrePersist
 */
public function prePersistCallback()
{
    $currentUser = /* ...... ????? ....... */ ;
    if ($currentUser->getId() != null) {
        $this->creationId = $currentUser->getId() ;
    } else {
        $this->creationId = 'unknown' ;
    }
    return $this;
}
Run Code Online (Sandbox Code Playgroud)

但我不知道如何检索连接的用户,或者如何自动将其注入实体中......我该怎么做?

yce*_*uto 6

您可以使用 Doctrine 实体侦听器/订阅者来注入安全令牌并获取当前登录的用户:

// src/AppBundle/EventListener/EntityListener.php
namespace AppBundle\EventListener;

use Doctrine\ORM\Event\LifecycleEventArgs;
use AppBundle\Entity\GenericEntity;
use Symfony\Component\Security\Core\Authentication\Token\Storage\TokenStorageInterface;

class EntityListener
{
    private $tokenStorage;

    public function __construct(TokenStorageInterface $tokenStorage = null) 
    {
        $this->tokenStorage = $tokenStorage;
    }

    public function prePersist(LifecycleEventArgs $args)
    {
        $entity = $args->getEntity();

        // only act on "GenericEntity"
        if (!$entity instanceof GenericEntity) {
            return;
        }

        if (null !== $currentUser = $this->getUser()) {
            $entity->setCreationId($currentUser->getId());
        } else {
            $entity->setCreationId(0);
        }
    }

    public function getUser()
    {
        if (!$this->tokenStorage) {
            throw new \LogicException('The SecurityBundle is not registered in your application.');
        }

        if (null === $token = $this->tokenStorage->getToken()) {
            return;
        }

        if (!is_object($user = $token->getUser())) {
            // e.g. anonymous authentication
            return;
        }

        return $user;
    }
}
Run Code Online (Sandbox Code Playgroud)

接下来注册你的监听器:

# app/config/services.yml
services:
    my.listener:
        class: AppBundle\EventListener\EntityListener
        arguments: ['@security.token_storage']
        tags:
            - { name: doctrine.event_listener, event: prePersist }
Run Code Online (Sandbox Code Playgroud)