简体   繁体   中英

Symfony 3 - Use session variables?

I would like to use session variables for my site.

I made :

$request = new Request();

    $session = $request->getSession();

    if ($session == null)
    {
        $session = new Session();
    }
$session->set('typeAuth','cas');

But in my controler, when I call this session variable by :

    $typeAuth = $_SESSION->get('typeAuth');

I've :

Notice: Undefined variable: session

And I don't understand why

You can directly inject the SessionInterface in your constructor, then use it as property of your service.

In example :

use Symfony\Component\HttpFoundation\Session\SessionInterface; // <--- use this namespace

class AuthCasService extends AuthAbstract implements AuthInterface {

    private $serializer;
    private $session;

    // Inject the SessionInterface ----------------------------------------------------------V-----------------------V
    public function __construct(EntityManagerInterface $em, SerializerInterface $serializer, SessionInterface $session)
    {
        $this->em = $em;
        $this->serializer = $serializer;
        $this->session = $session;
    }

    // Your methods ...
}

and then, in your method, remove $session = $request->getSession(); and use $this->session->set('foo', 'bar');

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