php 如何在 Symfony 中使用会话?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/1761552/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to use Sessions in Symfony?
提问by Harish Kurup
Like in classic PHP we use the magic variables to start and create sessions, so how to do that in Symfony?
就像在经典 PHP 中一样,我们使用魔法变量来启动和创建会话,那么如何在 Symfony 中做到这一点呢?
回答by Tac Tacelosky
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.session.get('foo', 'bar'); }}
回答by Franz
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);

