简体   繁体   中英

Symfony 3 - Cannot use session get user

I have a User entity on my project. 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
But when you retrieve the entity from session : Doctrine unit of work does not know it have to handle this entity

After that you should have some issues with Doctrine lazy loading.

Session is not good to store an entity.

A better solution is :

  • Inject Doctrine entity manager in your service
  • Only store id on session
  • On getUtilisateur method retrieve the user with id if not already done

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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