简体   繁体   English

Symfony 3 - 无法使用session get user

[英]Symfony 3 - Cannot use session get user

I have a User entity on my project. 我的项目中有一个User实体。 Each page load, I bother to recover the user with a query in the database. 每个页面加载,我懒得用数据库中的查询恢复用户。

My goal is to put it in session variable directly after it has logged in to simply get it back when I want. 我的目标是在登录后将其直接放入会话变量中,以便在我想要时将其恢复。

In my code, if I test this: 在我的代码中,如果我测试这个:

$user = $this->checkBDD($mail,$fredurne,$nomComplet);
        dump($user);

        $this->session->set('user',$user);

        $user = $this->session->get('user');
        dump($user);

I have : 我有 :

在此输入图像描述

So, the session seems work. 所以,会议似乎有效。

Now, I put it into application. 现在,我把它付诸实践。 I create a function: 我创建了一个函数:

$user = $this->getUtilisateur($mail,$fredurne,$nomComplet);
dump($user);

With

public function getUtilisateur($mail,$fredurne,$nomComplet)
    {
        if(!$this->session->has('user'))
        {
            dump("user not in session");
            $user = $this->checkBDD($mail,$fredurne,$nomComplet);
            $this->session->set('user',$user);
        }

        else
        {
            dump("user in session");
            $user = $this->session->get('user');
        }

        return $user;
    }

And I have : 我有 :

在此输入图像描述

So, I don't understand what's the problem 所以,我不明白这是什么问题

Problem : 问题:
Doctrine entity is stored on session but needs to be refreshed Doctrine实体存储在会话中,但需要刷新
But when you retrieve the entity from session : Doctrine unit of work does not know it have to handle this entity 但是当你从会话中检索实体时:Doctrine工作单元不知道它必须处理这个实体

After that you should have some issues with Doctrine lazy loading. 之后你应该对Doctrine延迟加载有一些问题。

Session is not good to store an entity. 会话不适合存储实体。

A better solution is : 更好的解决方案是:

  • Inject Doctrine entity manager in your service 在服务中注入Doctrine实体管理器
  • Only store id on session 仅在会话中存储ID
  • On getUtilisateur method retrieve the user with id if not already done getUtilisateur方法中检索具有id的用户(如果尚未完成)

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

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