将当前用户 ID 保存在存储库中

Saving current user id in repository

我尝试在 UserService 实体中保存用户字段的初始值。原因是,我在 EasyAdminBundle 中使用了这个实体,当我构建一个表单时,我想为 user_id(ManyToOne 到 User 实体)设置一个默认值。

...但我在保存过程中仍然看不到变化。

class UserServiceRepository extends ServiceEntityRepository
{

protected $_em;

public function __construct(RegistryInterface $registry)
{

    $this->_em = $this->entityManager;

    parent::__construct($registry, UserService::class);
}

// I override save method:
public function save(UserService $userService)
{
    // Get current user from security:
    $user = $this->get('security.token_storage')->getToken()->getUser();
    // set to useService...
    $userService->setUser($user);

        // and persist & flush:
        $this->_em->persist($userService);
        $this->_em->flush();


}
// I override save method:

您正在覆盖父级中不存在的方法,ServiceEntityRepository 和 EntityRepository 中都没有保存方法。那么,您所做工作的要点是什么?为什么要在服务存储库中设置默认 user_id?

更新:

services:
    my.listener:
        class: UserServiceListener
        arguments:
            - "@security.token_storage"
        tags:
            - { name: doctrine.event_listener, event: prePersist }

听众:

class UserServiceListener
{
    private $token_storage;

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

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

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

        $entity->setUser($this->token_storage->getToken()->getUser());
    }
}