我是否需要在需要访问会话的任何控制器上启动会话


Do I need to start the session at any controller where I need to access it?

我在控制器的indexAction中有以下代码,该索引是一个进程的起点(包括通过Ajax调用多个控制器):

$session = $request->getSession();
$currentData = [];
$session->set('currentData', $currentData);

现在假设我需要在另一个控制器中为currentData设置一个新值,我现在做的是:

$session = $request->getSession();
// get currentData from session for not override the values
$currentData = $session->get('currentData');
// sets the new value
$currentData['newValue'] = 1;
// save the var again and override currentData session
$session->set('currentData', $currentData);

关于这一点,正如标题所说,问题很简单:我是否需要在我需要访问会话的任何控制器上启动(每当我需要访问会话时一直调用$session = $request->getSession())会话?存在任何实现这一目标的最佳方法,还是我是做错了所有事情的人?有什么建议吗?

注意:我忘了说我正在谈论和使用Symfony 2.6.3

您不必这样做,但建议您这样做。从文档中:

虽然建议显式启动会话,但会话实际上将按需启动,也就是说,如果发出任何会话请求以读取/写入会话数据。

您确实需要使用 $session = $request->getSession()$session = $this->get('session')$session = new Symfony'Component'HttpFoundation'Session'Session(); 来获取Session容器。这与启动会话不同,这三种方式之间实际上没有区别。

这适用于任何Symfony 2.x版本。