我想在Symfony2中启用会话,但我不知道如何才能做到这一点。
我这样设置我的配置文件:
#app/config/config.yml
framework:
session:
name: session
cookie_lifetime: 0
cookie_httponly: true
但似乎我的会话仍然是禁用的,没有开始。我在控制器中测试了这段代码:
echo ( session_status() !== PHP_SESSION_ACTIVE )
? "Session is not started!"
: "Session OK";
返回"Session is not started!"只有当我设置:
时才有效if (session_status() == PHP_SESSION_NONE) {
session_start();
}
但这是非常丑陋的解决方案,特别是我在Symfony2中工作。你有什么主意吗?
你不需要激活它,它是symfony默认设置的。
默认条目是:
framework:
session: ~
你也不需要开始一个新的会话(事实上你会收到一个错误,因为它已经从symfony开始)。
15.04.2016编辑:
语法现在有点不同
控制器$session = $this->get('session');
树枝> :
你只需要从请求中获得控制器中的会话!
$session = $this->getRequest()->getSession();
。
在Twig中你可以通过
访问app.request.session
在我目前的项目中,我已经启用了这样的会话,它工作得很好:
(在框架选项下)
session:
handler_id: ~
cookie_domain: .st.dev
name: SFSESSID
cookie_lifetime: 0
save_path: "%kernel.cache_dir%/sessions"
gc_divisor: 2000
gc_maxlifetime: 86400
你也可以看看这个文档页
在app/config/config中。在Yml框架部分,你必须有一个会话项:
framework:
# ...
session: ~
看一下:http://symfony.com/doc/current/reference/configuration/framework.html#session
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');
如果您使用最新版本的Symfony2,则在其中读/写数据时会自动启动会话。
但是,您可以通过实例化一个会话变量来强制启动它:
$session = new Session();
$session->start();
你应该看一下医生。注意,Symfony会话与本机会话不同。
http://symfony.com/doc/current/components/http_foundation/sessions.html http://symfony.com/doc/current/components/http_foundation/session_php_bridge.html