Like in classic PHP we use the magic variables to start and create sessions, so how to do that in Symfony?
Asked
Active
Viewed 6.5k times
2 Answers
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
- 3,165
- 3
- 27
- 28
-
2**Symfony:** _because who really cares about the Law of Demeter anyway?_ – Jan 03 '14 at 21:23
-
6How 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
- 11,353
- 8
- 48
- 70
-
1In 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
-