[英]How to set session variables for all the controllers in Symfony2?
如何在控制器中創建和訪問Symfony 2會話變量。 我曾經這樣。
$session = new Session();
$session->start();
$session->set('loginUserId',$user['user_id']);
我想知道如何在所有控制器中使用以上會話變量進行訪問。
在控制器中的Symfony中使用會話的一種方法是:
設置:
$this->get('session')->set('loginUserId', $user['user_id']);
得到:
$this->get('session')->get('loginUserId');
如果使用標准框架版本
從文檔:
Symfony會話旨在替換一些本地PHP函數。 應用程序應避免使用session_start(),session_regenerate_id(),session_id(),session_name()和session_destroy(),而應使用以下部分中的API。
和:
雖然建議顯式啟動會話,但是實際上會根據需要啟動會話,也就是說,如果發出任何會話請求來讀取/寫入會話數據。
因此,會話將自動啟動,並且可以通過以下方式從控制器進行訪問:
public function indexAction(Request $request)
{
$session = $request->getSession();
...
}
要么:
public function indexAction()
{
$session = $this->getRequest()->getSession();
// or
$session = $this->get('session');
...
}
比:
// store an attribute for reuse during a later user request
$session->set('foo', 'bar');
// get the attribute set by another controller in another request
$foobar = $session->get('foobar');
// use a default value if the attribute doesn't exist
$filters = $session->get('filters', array());
http://symfony.com/doc/current/components/http_foundation/sessions.html
use Symfony\Component\HttpFoundation\Session\Session;
$session = new Session();
$session->start();
// set and get session attributes
$session->set('name', 'Drak');
$session->get('name');
// set flash messages
$session->getFlashBag()->add('notice', 'Profile updated');
// retrieve messages
foreach ($session->getFlashBag()->get('notice', array()) as $message) {
echo '<div class="flash-notice">'.$message.'</div>';
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.