32

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

Robert Wade
  • 4,611
  • 1
  • 12
  • 30
Harish Kurup
  • 6,455
  • 18
  • 61
  • 92

2 Answers2

80

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'); }}
Tac Tacelosky
  • 2,575
  • 3
  • 21
  • 21
  • 2
    **Symfony:** _because who really cares about the Law of Demeter anyway?_ – rdlowrey Jan 03 '14 at 21:23
  • 6
    How using sessions variables violates the Law of Demeter ? – Videl Feb 10 '14 at 17:46
  • 3
    @Videl it's not using sessions that violates LoD, its the abstraction layer from symfony. – Marcel Burkhard Jun 22 '15 at 12:59
  • 7
    `getRequest()` is deprecated as of Symfony 2.4. The proper way to do this now is to inject a Request into the controller and call `$request->getSession()`. http://api.symfony.com/2.0/Symfony/Component/HttpFoundation/Request.html#method_getSession – HPierce Aug 07 '15 at 18:03
  • This is literally the opposite of not caring about the law of demeter, the symfony framework is communicating with its own api – user3531149 Mar 17 '16 at 08:11
33

In your controller, you can access session variables through the user object.

// Get a session value
$name = $this->getUser()->getAttribute('name', 'default_value');
// Set a session value
$this->getUser()->setAttribute('name', $value);
Franz
  • 10,879
  • 7
  • 46
  • 66
  • 1
    In your view, you can access session variables through the `$sf_user` variable, just the same way you do with `$this->getUser()` in the controller. – Throoze Jan 02 '12 at 17:23
  • I don't think this will work if you don't have a user or a firewall. – Ascherer May 15 '15 at 05:28