Like in classic PHP we use the magic variables to start and create sessions, so how to do that in Symfony?
与经典PHP一样,我们使用魔术变量来启动和创建会话,那么如何在Symfony中执行此操作?
2 个解决方案
#1
32
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);
#2
80
In Symfony2, the syntax is different:
在Symfony2中,语法不同:
$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'):
您还可以从Twig获取会话变量,而无需显式传递会话变量(它位于全局“app”中):
{{ app.session.get('foo', 'bar'); }}
#1
32
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);
#2
80
In Symfony2, the syntax is different:
在Symfony2中,语法不同:
$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'):
您还可以从Twig获取会话变量,而无需显式传递会话变量(它位于全局“app”中):
{{ app.session.get('foo', 'bar'); }}