How to use Sessions in Symfony?

Harish Kurup picture Harish Kurup · Nov 19, 2009 · Viewed 63.6k times · Source

Like in classic PHP we use the magic variables to start and create sessions, so how to do that in Symfony?

Answer

Tac Tacelosky picture Tac Tacelosky · Jul 14, 2012

In Symfony2, the syntax is different:

$session = $this->getRequest()->getSession();

// store an attribute for reuse during a later user request
$session->set('foo', 'bar');

// in another controller for another request
$foo = $session->get('foo');

You can also get session variables from Twig, without having to pass the session variable explicitly (it's in the global 'app'):

{{ app.session.get('foo', 'bar'); }}