How to use Sessions in Symfony? [closed]

2020-02-08 09:52发布

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

2条回答
该账号已被封号
2楼-- · 2020-02-08 10:27

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);
查看更多
来,给爷笑一个
3楼-- · 2020-02-08 10:41

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'); }}
查看更多
登录 后发表回答