在Web應用中,session的重要性毋庸置疑。Yii 2中,使用Session類來管理session。
當使用者登入以後,Yii 2會調用到web\User->renewAuthStatus(),在這裡調用到session->get()函數時,在session->get()函數内部調用了Session->open(),将session資料加載進來。
Yii 2預設使用php.ini中的配置參數:
session.save_handler = files
;session.save_path = "/tmp"
也就是說預設将session資訊儲存到檔案,如果php.ini中沒有設定session.save_path的話,預設存儲路徑就是“C:\Users\目前使用者\AppData\Local\Temp”。
有些系統為了更好的管理session資料,會将其儲存到資料庫裡,則可以通過繼承Session類,并進行如下處理:
1、在子類的getUseCustomStorage()傳回true,表示使用自定義存儲方式;
2、在子類實作如下接口:openSession(),closeSession(), readSession(), writeSession(), destroySession() and gcSession();
這些接口的含義很清楚,一看函數名就知道了。
預設$app->session所指向的Session類執行個體,是在web\Application.php中的coreComponents()函數配置的:
public function coreComponents()
{
return array_merge(parent::coreComponents(), [
'request' => ['class' => 'yii\web\Request'],
'response' => ['class' => 'yii\web\Response'],
'session' => ['class' => 'yii\web\Session'],
'user' => ['class' => 'yii\web\User'],
'errorHandler' => ['class' => 'yii\web\ErrorHandler'],
]);
}
如果想用自己的Session類,則可在main.php中的components節點下,參考上述代碼配置自己的session類。
本文轉自 tywali 51CTO部落格,原文連結:http://blog.51cto.com/lancelot/1873244,如需轉載請自行聯系原作者