我需要在需要访问它的任何控制器上启动 session 吗?
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 时一直调用 $session = $request->getSession()
)session我需要访问它的控制器?存在实现此目标的最佳方法,还是我做错了?有什么建议吗?
注意:我忘了说我正在使用 Symfony 2.6.3
进行交流和工作
您不必这样做,但建议这样做。 From the docs:
While it is recommended to explicitly start a session, a session will actually start on demand, that is, if any session request is made to read/write session data.
您确实需要使用 $session = $request->getSession()
、$session = $this->get('session')
或 $session = new Symfony\Component\HttpFoundation\Session\Session();
获取 Session
容器。这与开始会话不同,这三种方式之间确实没有区别。
这适用于任何 Symfony 2.x 版本。
我在控制器的 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 时一直调用 $session = $request->getSession()
)session我需要访问它的控制器?存在实现此目标的最佳方法,还是我做错了?有什么建议吗?
注意:我忘了说我正在使用 Symfony 2.6.3
进行交流和工作您不必这样做,但建议这样做。 From the docs:
While it is recommended to explicitly start a session, a session will actually start on demand, that is, if any session request is made to read/write session data.
您确实需要使用 $session = $request->getSession()
、$session = $this->get('session')
或 $session = new Symfony\Component\HttpFoundation\Session\Session();
获取 Session
容器。这与开始会话不同,这三种方式之间确实没有区别。
这适用于任何 Symfony 2.x 版本。