類別 yii\web\DbSession
DbSession 繼承自 yii\web\Session,使用資料庫作為 session 資料儲存空間。
預設情況下,DbSession 將 session 資料儲存在名為 'session' 的 DB 資料表中。此資料表必須預先建立。資料表名稱可以通過設定 $sessionTable 更改。
以下範例展示如何配置應用程式使用 DbSession:在您的應用程式配置的 components
下新增以下內容
'session' => [
'class' => 'yii\web\DbSession',
// 'db' => 'mydb',
// 'sessionTable' => 'my_session',
]
DbSession 繼承自 yii\web\MultiFieldSession,因此允許將額外欄位儲存到 $sessionTable 中。有關更多詳細資訊,請參閱 yii\web\MultiFieldSession。
公開屬性
公開方法
Protected Methods
方法 | 描述 | 定義於 |
---|---|---|
composeFields() | 組成用於 session 寫入的儲存欄位集。 | yii\web\MultiFieldSession |
extractData() | 從儲存欄位集中提取 session 資料。 | yii\web\MultiFieldSession |
freeze() | 如果 session 已啟動,則無法編輯 session ini 設定。在 PHP 7.2+ 版本中,這會拋出例外。 | yii\web\Session |
getReadQuery() | 產生從資料庫取得 session 的查詢。 | yii\web\DbSession |
registerSessionHandler() | 註冊 session 處理常式。 | yii\web\Session |
typecastFields() | 方法在將 $fields 傳遞給 PDO 之前進行型別轉換。 | yii\web\DbSession |
unfreeze() | 啟動 session 並從暫時變數還原資料。 | yii\web\Session |
updateFlashCounters() | 更新快閃訊息的計數器並移除過期的快閃訊息。 | yii\web\Session |
Property Details
DB 連線物件或 DB 連線的應用程式元件 ID。在建立 DbSession 物件後,如果您想要變更此屬性,您應該只將其指定為 DB 連線物件。從 2.0.2 版本開始,這也可以是用於建立物件的組態陣列。
要寫入 session 資料表欄位的 session 欄位
儲存 session 資料的 DB 表格名稱。表格應預先建立如下
CREATE TABLE session
(
id CHAR(40) NOT NULL PRIMARY KEY,
expire INTEGER,
data BLOB
)
其中 'BLOB' 指的是您偏好的 DBMS 的 BLOB 類型。以下是一些常用的 DBMS 可以使用的 BLOB 類型
- MySQL: LONGBLOB
- PostgreSQL: BYTEA
- MSSQL: BLOB
在生產伺服器中使用 DbSession 時,我們建議您為 session 表格中的 'expire' 欄位建立 DB 索引,以提高效能。
請注意,根據 `session.hash_function` 的 php.ini 設定,您可能需要調整 `id` 欄位的長度。例如,如果 `session.hash_function=sha256`,您應該使用長度 64 而不是 40。
Method Details
Defined in: yii\base\Component::__call()
呼叫指定的非類別方法。
此方法將檢查是否有任何附加的行為具有指定的名稱方法,並在可用的情況下執行它。
請勿直接呼叫此方法,因為它是 PHP 魔術方法,當調用未知方法時會隱含地呼叫它。
public mixed __call ( $name, $params ) | ||
$name | string |
方法名稱 |
$params | array |
方法參數 |
return | mixed |
方法傳回值 |
---|---|---|
throws | yii\base\UnknownMethodException |
當呼叫未知方法時 |
public function __call($name, $params)
{
$this->ensureBehaviors();
foreach ($this->_behaviors as $object) {
if ($object->hasMethod($name)) {
return call_user_func_array([$object, $name], $params);
}
}
throw new UnknownMethodException('Calling unknown method: ' . get_class($this) . "::$name()");
}
public void __clone ( ) |
public function __clone()
{
$this->_events = [];
$this->_eventWildcards = [];
$this->_behaviors = null;
}
Defined in: yii\base\BaseObject::__construct()
建構子。
預設實作會執行兩件事:
- 使用給定的組態
$config
初始化物件。 - 呼叫 init()。
如果在子類別中覆寫此方法,建議
- 建構子的最後一個參數是一個組態陣列,就像這裡的
$config
一樣。 - 在建構子的結尾呼叫父類別的實作。
public void __construct ( $config = [] ) | ||
$config | array |
將用於初始化物件屬性的名稱-值配對 |
public function __construct($config = [])
{
if (!empty($config)) {
Yii::configure($this, $config);
}
$this->init();
}
Defined in: yii\base\Component::__get()
傳回組件屬性的值。
此方法將依以下順序檢查並採取相應的行動:
- 由 getter 定義的屬性:傳回 getter 結果
- 行為的屬性:傳回行為屬性值
請勿直接呼叫此方法,因為它是 PHP 魔術方法,當執行 $value = $component->property;
時會隱含地呼叫它。
另請參閱 __set()。
public mixed __get ( $name ) | ||
$name | string |
屬性名稱 |
return | mixed |
屬性值或行為的屬性值 |
---|---|---|
throws | yii\base\UnknownPropertyException |
如果未定義屬性 |
throws | yii\base\InvalidCallException |
如果屬性為唯寫。 |
public function __get($name)
{
$getter = 'get' . $name;
if (method_exists($this, $getter)) {
// read property, e.g. getName()
return $this->$getter();
}
// behavior property
$this->ensureBehaviors();
foreach ($this->_behaviors as $behavior) {
if ($behavior->canGetProperty($name)) {
return $behavior->$name;
}
}
if (method_exists($this, 'set' . $name)) {
throw new InvalidCallException('Getting write-only property: ' . get_class($this) . '::' . $name);
}
throw new UnknownPropertyException('Getting unknown property: ' . get_class($this) . '::' . $name);
}
Defined in: yii\base\Component::__isset()
檢查屬性是否已設定,即已定義且非 null。
此方法將依以下順序檢查並採取相應的行動:
- 由 setter 定義的屬性:傳回屬性是否已設定
- 行為的屬性:傳回屬性是否已設定
- 對於不存在的屬性,傳回
false
請勿直接呼叫此方法,因為它是 PHP 魔術方法,當執行 isset($component->property)
時會隱含地呼叫它。
public boolean __isset ( $name ) | ||
$name | string |
屬性名稱或事件名稱 |
return | boolean |
指定的屬性是否已設定 |
---|
public function __isset($name)
{
$getter = 'get' . $name;
if (method_exists($this, $getter)) {
return $this->$getter() !== null;
}
// behavior property
$this->ensureBehaviors();
foreach ($this->_behaviors as $behavior) {
if ($behavior->canGetProperty($name)) {
return $behavior->$name !== null;
}
}
return false;
}
Defined in: yii\base\Component::__set()
設定組件屬性的值。
此方法將依以下順序檢查並採取相應的行動:
- 由 setter 定義的屬性:設定屬性值
- 格式為 "on xyz" 的事件:將處理常式附加到事件 "xyz"
- 格式為 "as xyz" 的行為:附加名為 "xyz" 的行為
- 行為的屬性:設定行為屬性值
請勿直接呼叫此方法,因為它是 PHP 魔術方法,當執行 $component->property = $value;
時會隱含地呼叫它。
另請參閱 __get()。
public void __set ( $name, $value ) | ||
$name | string |
屬性名稱或事件名稱 |
$value | mixed |
屬性值 |
throws | yii\base\UnknownPropertyException |
如果未定義屬性 |
---|---|---|
throws | yii\base\InvalidCallException |
如果屬性為唯讀。 |
public function __set($name, $value)
{
$setter = 'set' . $name;
if (method_exists($this, $setter)) {
// set property
$this->$setter($value);
return;
} elseif (strncmp($name, 'on ', 3) === 0) {
// on event: attach event handler
$this->on(trim(substr($name, 3)), $value);
return;
} elseif (strncmp($name, 'as ', 3) === 0) {
// as behavior: attach behavior
$name = trim(substr($name, 3));
$this->attachBehavior($name, $value instanceof Behavior ? $value : Yii::createObject($value));
return;
}
// behavior property
$this->ensureBehaviors();
foreach ($this->_behaviors as $behavior) {
if ($behavior->canSetProperty($name)) {
$behavior->$name = $value;
return;
}
}
if (method_exists($this, 'get' . $name)) {
throw new InvalidCallException('Setting read-only property: ' . get_class($this) . '::' . $name);
}
throw new UnknownPropertyException('Setting unknown property: ' . get_class($this) . '::' . $name);
}
Defined in: yii\base\Component::__unset()
將組件屬性設定為 null。
此方法將依以下順序檢查並採取相應的行動:
- 由 setter 定義的屬性:將屬性值設定為 null
- 行為的屬性:將屬性值設定為 null
請勿直接呼叫此方法,因為它是 PHP 魔術方法,當執行 unset($component->property)
時會隱含地呼叫它。
public void __unset ( $name ) | ||
$name | string |
屬性名稱 |
throws | yii\base\InvalidCallException |
如果屬性為唯讀。 |
---|
public function __unset($name)
{
$setter = 'set' . $name;
if (method_exists($this, $setter)) {
$this->$setter(null);
return;
}
// behavior property
$this->ensureBehaviors();
foreach ($this->_behaviors as $behavior) {
if ($behavior->canSetProperty($name)) {
$behavior->$name = null;
return;
}
}
throw new InvalidCallException('Unsetting an unknown or read-only property: ' . get_class($this) . '::' . $name);
}
public void addFlash ( $key, $value = true, $removeAfterAccess = true ) | ||
$key | string |
識別快閃訊息的鍵。 |
$value | mixed |
快閃訊息 |
$removeAfterAccess | boolean |
快閃訊息是否應僅在被存取後才自動移除。如果為 false,快閃訊息將在下一個請求後自動移除,無論是否被存取。如果為 true(預設值),快閃訊息將保留到被存取之後。 |
public function addFlash($key, $value = true, $removeAfterAccess = true)
{
$counters = $this->get($this->flashParam, []);
$counters[$key] = $removeAfterAccess ? -1 : 0;
$_SESSION[$this->flashParam] = $counters;
if (empty($_SESSION[$key])) {
$_SESSION[$key] = [$value];
} elseif (is_array($_SESSION[$key])) {
$_SESSION[$key][] = $value;
} else {
$_SESSION[$key] = [$_SESSION[$key], $value];
}
}
Defined in: yii\base\Component::attachBehavior()
將行為附加到此組件。
此方法將根據給定的組態建立行為物件。之後,將透過呼叫 yii\base\Behavior::attach() 方法將行為物件附加到此元件。
另請參閱 detachBehavior()。
public yii\base\Behavior attachBehavior ( $name, $behavior ) | ||
$name | string |
行為的名稱。 |
$behavior | string|array|yii\base\Behavior |
行為組態。這可以是以下其中之一:
|
return | yii\base\Behavior |
行為物件 |
---|
public function attachBehavior($name, $behavior)
{
$this->ensureBehaviors();
return $this->attachBehaviorInternal($name, $behavior);
}
Defined in: yii\base\Component::attachBehaviors()
將行為列表附加到組件。
每個行為都以其名稱索引,並且應該是一個 yii\base\Behavior 物件、一個指定行為類別的字串,或一個用於建立行為的組態陣列。
另請參閱 attachBehavior()。
public void attachBehaviors ( $behaviors ) | ||
$behaviors | array |
要附加到元件的行為列表 |
public function attachBehaviors($behaviors)
{
$this->ensureBehaviors();
foreach ($behaviors as $name => $behavior) {
$this->attachBehaviorInternal($name, $behavior);
}
}
Defined in: yii\base\Component::behaviors()
傳回此組件應表現為的行為列表。
子類別可以覆寫此方法以指定它們想要表現為的行為。
此方法的傳回值應該是一個行為物件或組態陣列,以行為名稱索引。行為組態可以是指定行為類別的字串,或以下結構的陣列:
'behaviorName' => [
'class' => 'BehaviorClass',
'property1' => 'value1',
'property2' => 'value2',
]
請注意,行為類別必須從 yii\base\Behavior 擴展。行為可以使用名稱或匿名方式附加。當名稱用作陣列金鑰時,使用此名稱,稍後可以使用 getBehavior() 檢索行為,或使用 detachBehavior() 分離行為。匿名行為無法檢索或分離。
在此方法中宣告的行為將自動(按需)附加到元件。
public array behaviors ( ) | ||
return | array |
行為組態。 |
---|
public function behaviors()
{
return [];
}
Defined in: yii\base\Component::canGetProperty()
傳回指示屬性是否可讀取的值。
如果符合以下條件,則可以讀取屬性:
- 類別具有與指定名稱相關聯的 getter 方法(在這種情況下,屬性名稱不區分大小寫);
- 類別具有具有指定名稱的成員變數(當
$checkVars
為 true 時); - 附加的行為具有給定名稱的可讀屬性(當
$checkBehaviors
為 true 時)。
另請參閱 canSetProperty()。
public boolean canGetProperty ( $name, $checkVars = true, $checkBehaviors = true ) | ||
$name | string |
屬性名稱 |
$checkVars | boolean |
是否將成員變數視為屬性 |
$checkBehaviors | boolean |
是否將行為的屬性視為此元件的屬性 |
return | boolean |
屬性是否可以讀取 |
---|
public function canGetProperty($name, $checkVars = true, $checkBehaviors = true)
{
if (method_exists($this, 'get' . $name) || $checkVars && property_exists($this, $name)) {
return true;
} elseif ($checkBehaviors) {
$this->ensureBehaviors();
foreach ($this->_behaviors as $behavior) {
if ($behavior->canGetProperty($name, $checkVars)) {
return true;
}
}
}
return false;
}
Defined in: yii\base\Component::canSetProperty()
傳回指示屬性是否可設定的值。
如果符合以下條件,則可以寫入屬性:
- 類別具有與指定名稱相關聯的 setter 方法(在這種情況下,屬性名稱不區分大小寫);
- 類別具有具有指定名稱的成員變數(當
$checkVars
為 true 時); - 附加的行為具有給定名稱的可寫屬性(當
$checkBehaviors
為 true 時)。
另請參閱 canGetProperty()。
public boolean canSetProperty ( $name, $checkVars = true, $checkBehaviors = true ) | ||
$name | string |
屬性名稱 |
$checkVars | boolean |
是否將成員變數視為屬性 |
$checkBehaviors | boolean |
是否將行為的屬性視為此元件的屬性 |
return | boolean |
屬性是否可以寫入 |
---|
public function canSetProperty($name, $checkVars = true, $checkBehaviors = true)
{
if (method_exists($this, 'set' . $name) || $checkVars && property_exists($this, $name)) {
return true;
} elseif ($checkBehaviors) {
$this->ensureBehaviors();
foreach ($this->_behaviors as $behavior) {
if ($behavior->canSetProperty($name, $checkVars)) {
return true;
}
}
}
return false;
}
::class
。
Defined in: yii\base\BaseObject::className()
傳回此類別的完整限定名稱。
public static string className ( ) | ||
return | string |
此類別的完整限定名稱。 |
---|
public static function className()
{
return get_called_class();
}
結束當前 session 並儲存 session 資料。
public void close ( ) |
public function close()
{
if ($this->getIsActive()) {
// prepare writeCallback fields before session closes
$this->fields = $this->composeFields();
YII_DEBUG ? session_write_close() : @session_write_close();
}
}
Defined in: yii\web\MultiFieldSession::composeFields()
組成用於 session 寫入的儲存欄位集。
protected array composeFields ( $id = null, $data = null ) | ||
$id | string|null |
可選的 session ID |
$data | string|null |
可選的 session 資料 |
return | array |
儲存欄位 |
---|
protected function composeFields($id = null, $data = null)
{
$fields = $this->writeCallback ? call_user_func($this->writeCallback, $this) : [];
if ($id !== null) {
$fields['id'] = $id;
}
if ($data !== null) {
$fields['data'] = $data;
}
return $fields;
}
public integer count ( ) | ||
return | integer |
Session 中的項目數量。 |
---|
#[\ReturnTypeWillChange]
public function count()
{
return $this->getCount();
}
定義於: yii\web\Session::destroy()
釋放所有 session 變數並銷毀所有註冊到 session 的資料。
當 session 未啟用時,此方法無效。請確保在調用此方法之前先調用 open()。
另請參閱
public void destroy ( ) |
public function destroy()
{
if ($this->getIsActive()) {
$sessionId = session_id();
$this->close();
$this->setId($sessionId);
$this->open();
session_unset();
session_destroy();
$this->setId($sessionId);
}
}
public yii\base\Behavior|null detachBehavior ( $name ) | ||
$name | string |
Behavior 的名稱。 |
return | yii\base\Behavior|null |
已分離的 behavior。如果 behavior 不存在則為 Null。 |
---|
public function detachBehavior($name)
{
$this->ensureBehaviors();
if (isset($this->_behaviors[$name])) {
$behavior = $this->_behaviors[$name];
unset($this->_behaviors[$name]);
$behavior->detach();
return $behavior;
}
return null;
}
定義於: yii\base\Component::detachBehaviors()
從組件分離所有行為。
public void detachBehaviors ( ) |
public function detachBehaviors()
{
$this->ensureBehaviors();
foreach ($this->_behaviors as $name => $behavior) {
$this->detachBehavior($name);
}
}
定義於: yii\base\Component::ensureBehaviors()
確保在 behaviors() 中宣告的行為已附加到此組件。
public void ensureBehaviors ( ) |
public function ensureBehaviors()
{
if ($this->_behaviors === null) {
$this->_behaviors = [];
foreach ($this->behaviors() as $name => $behavior) {
$this->attachBehaviorInternal($name, $behavior);
}
}
}
定義於: yii\web\MultiFieldSession::extractData()
從儲存欄位集中提取 session 資料。
protected string extractData ( $fields ) | ||
$fields | array |
儲存欄位。 |
return | string |
Session 資料。 |
---|
protected function extractData($fields)
{
if ($this->readCallback !== null) {
if (!isset($fields['data'])) {
$fields['data'] = '';
}
$extraData = call_user_func($this->readCallback, $fields);
if (!empty($extraData)) {
session_decode($fields['data']);
$_SESSION = array_merge((array) $_SESSION, (array) $extraData);
return session_encode();
}
return $fields['data'];
}
return isset($fields['data']) ? $fields['data'] : '';
}
定義於: yii\web\Session::freeze()
如果 session 已啟動,則無法編輯 session ini 設定。在 PHP 7.2+ 版本中,這會拋出例外。
此函數將 session 資料儲存到暫時變數並停止 session。
protected void freeze ( ) |
protected function freeze()
{
if ($this->getIsActive()) {
if (isset($_SESSION)) {
$this->_frozenSessionData = $_SESSION;
}
$this->close();
Yii::info('Session frozen', __METHOD__);
}
}
public mixed get ( $key, $defaultValue = null ) | ||
$key | string |
Session 變數名稱 |
$defaultValue | mixed |
當 session 變數不存在時要返回的預設值。 |
return | mixed |
session 變數值,如果 session 變數不存在則返回 $defaultValue。 |
---|
public function get($key, $defaultValue = null)
{
$this->open();
return isset($_SESSION[$key]) ? $_SESSION[$key] : $defaultValue;
}
定義於: yii\web\Session::getAllFlashes()
傳回所有快閃訊息。
您可以使用此方法在視圖檔案中顯示所有快閃訊息
<?php
foreach (Yii::$app->session->getAllFlashes() as $key => $message) {
echo '<div class="alert alert-' . $key . '">' . $message . '</div>';
} ?>
透過以上程式碼,您可以使用 bootstrap alert 類別,例如 success
、info
、danger
作為快閃訊息的鍵,以影響 div 的顏色。
請注意,如果您使用 addFlash(),$message
將會是一個陣列,您將必須調整以上程式碼。
另請參閱
public array getAllFlashes ( $delete = false ) | ||
$delete | boolean |
是否在此方法調用後立即刪除快閃訊息。如果為 false,快閃訊息將在下一個請求中自動刪除。 |
return | array |
快閃訊息 (鍵 => 訊息 或 鍵 => [訊息1, 訊息2]). |
---|
public function getAllFlashes($delete = false)
{
$counters = $this->get($this->flashParam, []);
$flashes = [];
foreach (array_keys($counters) as $key) {
if (array_key_exists($key, $_SESSION)) {
$flashes[$key] = $_SESSION[$key];
if ($delete) {
unset($counters[$key], $_SESSION[$key]);
} elseif ($counters[$key] < 0) {
// mark for deletion in the next request
$counters[$key] = 1;
}
} else {
unset($counters[$key]);
}
}
$_SESSION[$this->flashParam] = $counters;
return $flashes;
}
定義於: yii\base\Component::getBehavior()
傳回指定的行為物件。
public yii\base\Behavior|null getBehavior ( $name ) | ||
$name | string |
Behavior 名稱 |
return | yii\base\Behavior|null |
behavior 物件,如果 behavior 不存在則為 null |
---|
public function getBehavior($name)
{
$this->ensureBehaviors();
return isset($this->_behaviors[$name]) ? $this->_behaviors[$name] : null;
}
定義於: yii\base\Component::getBehaviors()
傳回附加到此元件的所有行為。
public yii\base\Behavior[] getBehaviors ( ) | ||
return | yii\base\Behavior[] |
附加到此組件的 behavior 列表 |
---|
public function getBehaviors()
{
$this->ensureBehaviors();
return $this->_behaviors;
}
定義於: yii\web\Session::getCacheLimiter()
傳回目前的快取限制器
public string getCacheLimiter ( ) | ||
return | string |
目前的快取限制器 |
---|
public function getCacheLimiter()
{
return session_cache_limiter();
}
定義於: yii\web\Session::getCookieParams()
另請參閱 https://php.dev.org.tw/manual/en/function.session-get-cookie-params.php。
public array getCookieParams ( ) | ||
return | array |
session cookie 參數。 |
---|
public function getCookieParams()
{
return array_merge(session_get_cookie_params(), array_change_key_case($this->_cookieParams));
}
定義於: yii\web\Session::getCount()
傳回 session 中的項目數。
public integer getCount ( ) | ||
return | integer |
session 變數的數量 |
---|
public function getCount()
{
$this->open();
return count($_SESSION);
}
public mixed getFlash ( $key, $defaultValue = null, $delete = false ) | ||
$key | string |
用於識別快閃訊息的鍵 |
$defaultValue | mixed |
如果快閃訊息不存在,則返回的值。 |
$delete | boolean |
是否在此方法調用後立即刪除此快閃訊息。如果為 false,快閃訊息將在下一個請求中自動刪除。 |
return | mixed |
快閃訊息,如果使用了 addFlash 則為訊息陣列 |
---|
public function getFlash($key, $defaultValue = null, $delete = false)
{
$counters = $this->get($this->flashParam, []);
if (isset($counters[$key])) {
$value = $this->get($key, $defaultValue);
if ($delete) {
$this->removeFlash($key);
} elseif ($counters[$key] < 0) {
// mark for deletion in the next request
$counters[$key] = 1;
$_SESSION[$this->flashParam] = $counters;
}
return $value;
}
return $defaultValue;
}
public float getGCProbability ( ) | ||
return | float |
每次 session 初始化時啟動 GC (垃圾回收) 程序的機率 (百分比)。 |
---|
public function getGCProbability()
{
return (float) (ini_get('session.gc_probability') / ini_get('session.gc_divisor') * 100);
}
定義於: yii\web\Session::getHasSessionId()
傳回一個值,指示目前請求是否已傳送 session ID。
預設實作將使用 session 名稱檢查 cookie 和 $_GET。如果您透過其他方式發送 session ID,您可能需要覆寫此方法或調用 setHasSessionId() 以明確設定是否已發送 session ID。
public boolean getHasSessionId ( ) | ||
return | boolean |
目前請求是否已傳送 session ID。 |
---|
public function getHasSessionId()
{
if ($this->_hasSessionId === null) {
$name = $this->getName();
$request = Yii::$app->getRequest();
if (!empty($_COOKIE[$name]) && ini_get('session.use_cookies')) {
$this->_hasSessionId = true;
} elseif (!ini_get('session.use_only_cookies') && ini_get('session.use_trans_sid')) {
$this->_hasSessionId = $request->get($name) != '';
} else {
$this->_hasSessionId = false;
}
}
return $this->_hasSessionId;
}
public string getId ( ) | ||
return | string |
目前的 session ID |
---|
public function getId()
{
return session_id();
}
public boolean getIsActive ( ) | ||
return | boolean |
Session 是否已啟動 |
---|
public function getIsActive()
{
return session_status() === PHP_SESSION_ACTIVE;
}
public yii\web\SessionIterator getIterator ( ) | ||
return | yii\web\SessionIterator |
用於遍歷 session 變數的迭代器。 |
---|
#[\ReturnTypeWillChange]
public function getIterator()
{
$this->open();
return new SessionIterator();
}
public string getName ( ) | ||
return | string |
目前的 session 名稱 |
---|
public function getName()
{
return session_name();
}
產生從資料庫取得 session 的查詢。
protected yii\db\Query getReadQuery ( $id ) | ||
$id | string |
session 的 id |
protected function getReadQuery($id)
{
return (new Query())
->from($this->sessionTable)
->where('[[expire]]>:expire AND [[id]]=:id', [':expire' => time(), ':id' => $id]);
}
public string getSavePath ( ) | ||
return | string |
目前的 session 儲存路徑,預設為 '/tmp'。 |
---|
public function getSavePath()
{
return session_save_path();
}
public integer getTimeout ( ) | ||
return | integer |
資料將被視為「垃圾」並被清除之前的秒數。預設值為 1440 秒(或 php.ini 中設定的 "session.gc_maxlifetime" 值)。 |
---|
public function getTimeout()
{
return (int) ini_get('session.gc_maxlifetime');
}
public boolean|null getUseCookies ( ) | ||
return | boolean|null |
指示是否應使用 cookies 儲存 session ID 的值。 |
---|
public function getUseCookies()
{
if (ini_get('session.use_cookies') === '0') {
return false;
} elseif (ini_get('session.use_only_cookies') === '1') {
return true;
}
return null;
}
定義於: yii\web\MultiFieldSession::getUseCustomStorage()
傳回一個值,指示是否使用自訂 session 儲存。
此方法覆寫了父類別的實作,並且總是返回 true。
public boolean getUseCustomStorage ( ) | ||
return | boolean |
是否使用自訂儲存空間。 |
---|
public function getUseCustomStorage()
{
return true;
}
public boolean getUseStrictMode ( ) | ||
return | boolean |
是否啟用嚴格模式。 |
---|
public function getUseStrictMode()
{
if (PHP_VERSION_ID < 50502) {
return self::$_useStrictModePolyfill;
}
return (bool)ini_get('session.use_strict_mode');
}
public boolean getUseTransparentSessionID ( ) | ||
return | boolean |
是否啟用透明 sid 支援,預設為 false。 |
---|
public function getUseTransparentSessionID()
{
return ini_get('session.use_trans_sid') == 1;
}
public boolean has ( $key ) | ||
$key | mixed |
Session 變數名稱 |
return | boolean |
是否有指定的 session 變數 |
---|
public function has($key)
{
$this->open();
return isset($_SESSION[$key]);
}
定義於: yii\base\Component::hasEventHandlers()
傳回一個值,指示是否有名稱事件附加任何處理常式。
public boolean hasEventHandlers ( $name ) | ||
$name | string |
事件名稱 |
return | boolean |
是否有任何處理器附加到事件。 |
---|
public function hasEventHandlers($name)
{
$this->ensureBehaviors();
if (!empty($this->_events[$name])) {
return true;
}
foreach ($this->_eventWildcards as $wildcard => $handlers) {
if (!empty($handlers) && StringHelper::matchWildcard($wildcard, $name)) {
return true;
}
}
return Event::hasHandlers($this, $name);
}
定義於: yii\web\Session::hasFlash()
傳回一個值,指示是否有與指定金鑰相關聯的快閃訊息。
public boolean hasFlash ( $key ) | ||
$key | string |
識別快閃訊息類型的鍵 |
return | boolean |
在指定的鍵下是否存在任何快閃訊息 |
---|
public function hasFlash($key)
{
return $this->getFlash($key) !== null;
}
定義於: yii\base\Component::hasMethod()
傳回一個值,指示是否已定義方法。
如果滿足以下條件,則定義了方法:
- 類別具有指定名稱的方法
- 當
$checkBehaviors
為 true 時,附加的 behavior 具有給定名稱的方法。
public boolean hasMethod ( $name, $checkBehaviors = true ) | ||
$name | string |
屬性名稱 |
$checkBehaviors | boolean |
是否將 behavior 的方法視為此組件的方法 |
return | boolean |
方法是否已定義 |
---|
public function hasMethod($name, $checkBehaviors = true)
{
if (method_exists($this, $name)) {
return true;
} elseif ($checkBehaviors) {
$this->ensureBehaviors();
foreach ($this->_behaviors as $behavior) {
if ($behavior->hasMethod($name)) {
return true;
}
}
}
return false;
}
定義於: yii\base\Component::hasProperty()
傳回一個值,指示是否已为此元件定義屬性。
如果滿足以下條件,則定義了屬性:
- 類別具有與指定名稱關聯的 getter 或 setter 方法(在這種情況下,屬性名稱不區分大小寫);
- 類別具有具有指定名稱的成員變數(當
$checkVars
為 true 時); - 當
$checkBehaviors
為 true 時,附加的 behavior 具有給定名稱的屬性。
另請參閱
public boolean hasProperty ( $name, $checkVars = true, $checkBehaviors = true ) | ||
$name | string |
屬性名稱 |
$checkVars | boolean |
是否將成員變數視為屬性 |
$checkBehaviors | boolean |
是否將行為的屬性視為此元件的屬性 |
return | boolean |
屬性是否已定義 |
---|
public function hasProperty($name, $checkVars = true, $checkBehaviors = true)
{
return $this->canGetProperty($name, $checkVars, $checkBehaviors) || $this->canSetProperty($name, false, $checkBehaviors);
}
初始化 DbSession 元件。
此方法將初始化 $db 屬性,以確保它引用有效的 DB 連線。
public void init ( ) | ||
throws | yii\base\InvalidConfigException |
如果 $db 無效。 |
---|
public function init()
{
parent::init();
$this->db = Instance::ensure($this->db, Connection::className());
}
定義於: yii\base\Component::off()
從此元件分離現有的事件處理常式。
此方法與 on() 相反。
注意:如果為事件名稱傳遞了萬用字元模式,則只會移除使用此萬用字元註冊的處理器,而使用與此萬用字元匹配的純名稱註冊的處理器將保留。
另請參閱 on()。
public boolean off ( $name, $handler = null ) | ||
$name | string |
事件名稱 |
$handler | callable|null |
要移除的事件處理器。如果為 null,則會移除附加到命名事件的所有處理器。 |
return | boolean |
如果找到並分離了處理器 |
---|
public function off($name, $handler = null)
{
$this->ensureBehaviors();
if (empty($this->_events[$name]) && empty($this->_eventWildcards[$name])) {
return false;
}
if ($handler === null) {
unset($this->_events[$name], $this->_eventWildcards[$name]);
return true;
}
$removed = false;
// plain event names
if (isset($this->_events[$name])) {
foreach ($this->_events[$name] as $i => $event) {
if ($event[0] === $handler) {
unset($this->_events[$name][$i]);
$removed = true;
}
}
if ($removed) {
$this->_events[$name] = array_values($this->_events[$name]);
return true;
}
}
// wildcard event names
if (isset($this->_eventWildcards[$name])) {
foreach ($this->_eventWildcards[$name] as $i => $event) {
if ($event[0] === $handler) {
unset($this->_eventWildcards[$name][$i]);
$removed = true;
}
}
if ($removed) {
$this->_eventWildcards[$name] = array_values($this->_eventWildcards[$name]);
// remove empty wildcards to save future redundant regex checks:
if (empty($this->_eventWildcards[$name])) {
unset($this->_eventWildcards[$name]);
}
}
}
return $removed;
}
定義於: yii\web\Session::offsetExists()
此方法為介面 ArrayAccess 所需。
public boolean offsetExists ( $offset ) | ||
$offset | integer|string |
要檢查的偏移量 |
#[\ReturnTypeWillChange]
public function offsetExists($offset)
{
$this->open();
return isset($_SESSION[$offset]);
}
定義於: yii\web\Session::offsetGet()
此方法為介面 ArrayAccess 所需。
public mixed offsetGet ( $offset ) | ||
$offset | integer|string |
檢索元素的偏移量。 |
return | mixed |
偏移量上的元素;如果在該偏移量上找不到元素,則為 null |
---|
#[\ReturnTypeWillChange]
public function offsetGet($offset)
{
$this->open();
return isset($_SESSION[$offset]) ? $_SESSION[$offset] : null;
}
定義於: yii\web\Session::offsetSet()
此方法為介面 ArrayAccess 所需。
public void offsetSet ( $offset, $item ) | ||
$offset | integer|string |
設定元素的偏移量 |
$item | mixed |
元素值 |
#[\ReturnTypeWillChange]
public function offsetSet($offset, $item)
{
$this->open();
$_SESSION[$offset] = $item;
}
定義於: yii\web\Session::offsetUnset()
此方法為介面 ArrayAccess 所需。
public void offsetUnset ( $offset ) | ||
$offset | integer|string |
取消設定元素的偏移量 |
#[\ReturnTypeWillChange]
public function offsetUnset($offset)
{
$this->open();
unset($_SESSION[$offset]);
}
將事件處理常式附加到事件。
事件處理器必須是有效的 PHP 回呼。以下是一些範例
function ($event) { ... } // anonymous function
[$object, 'handleClick'] // $object->handleClick()
['Page', 'handleClick'] // Page::handleClick()
'handleClick' // global function handleClick()
事件處理器必須使用以下簽章定義:
function ($event)
其中 $event
是一個 yii\base\Event 物件,其中包含與事件相關聯的參數。
自 2.0.14 版本起,您可以將事件名稱指定為萬用字元模式
$component->on('event.group.*', function ($event) {
Yii::trace($event->name . ' is triggered.');
});
另請參閱 off()。
public void on ( $name, $handler, $data = null, $append = true ) | ||
$name | string |
事件名稱 |
$handler | callable |
事件處理器 |
$data | mixed |
當事件觸發時要傳遞給事件處理器的資料。當事件處理器被調用時,可以透過 yii\base\Event::$data 存取此資料。 |
$append | boolean |
是否將新的事件處理器附加到現有的處理器列表末尾。如果為 false,新的處理器將被插入到現有處理器列表的開頭。 |
public function on($name, $handler, $data = null, $append = true)
{
$this->ensureBehaviors();
if (strpos($name, '*') !== false) {
if ($append || empty($this->_eventWildcards[$name])) {
$this->_eventWildcards[$name][] = [$handler, $data];
} else {
array_unshift($this->_eventWildcards[$name], [$handler, $data]);
}
return;
}
if ($append || empty($this->_events[$name])) {
$this->_events[$name][] = [$handler, $data];
} else {
array_unshift($this->_events[$name], [$handler, $data]);
}
}
啟動 session。
public void open ( ) |
public function open()
{
if ($this->getIsActive()) {
return;
}
$this->registerSessionHandler();
$this->setCookieParamsInternal();
YII_DEBUG ? session_start() : @session_start();
if ($this->getUseStrictMode() && $this->_forceRegenerateId) {
$this->regenerateID();
$this->_forceRegenerateId = null;
}
if ($this->getIsActive()) {
Yii::info('Session started', __METHOD__);
$this->updateFlashCounters();
} else {
$error = error_get_last();
$message = isset($error['message']) ? $error['message'] : 'Failed to start session.';
Yii::error($message, __METHOD__);
}
}
用新產生的 session ID 更新目前的 session ID。
請參考 https://php.dev.org.tw/session_regenerate_id 以取得更多詳細資訊。
public void regenerateID ( $deleteOldSession = false ) | ||
$deleteOldSession | boolean |
是否刪除舊的關聯 session 檔案。 |
public function regenerateID($deleteOldSession = false)
{
$oldID = session_id();
// if no session is started, there is nothing to regenerate
if (empty($oldID)) {
return;
}
parent::regenerateID(false);
$newID = session_id();
// if session id regeneration failed, no need to create/update it.
if (empty($newID)) {
Yii::warning('Failed to generate new session ID', __METHOD__);
return;
}
$row = $this->db->useMaster(function () use ($oldID) {
return (new Query())->from($this->sessionTable)
->where(['id' => $oldID])
->createCommand($this->db)
->queryOne();
});
if ($row !== false && $this->getIsActive()) {
if ($deleteOldSession) {
$this->db->createCommand()
->update($this->sessionTable, ['id' => $newID], ['id' => $oldID])
->execute();
} else {
$row['id'] = $newID;
$this->db->createCommand()
->insert($this->sessionTable, $row)
->execute();
}
}
}
定義於: yii\web\Session::registerSessionHandler()
註冊 session 處理常式。
protected void registerSessionHandler ( ) | ||
throws | yii\base\InvalidConfigException |
---|
protected function registerSessionHandler()
{
$sessionModuleName = session_module_name();
if (static::$_originalSessionModule === null) {
static::$_originalSessionModule = $sessionModuleName;
}
if ($this->handler !== null) {
if (!is_object($this->handler)) {
$this->handler = Yii::createObject($this->handler);
}
if (!$this->handler instanceof \SessionHandlerInterface) {
throw new InvalidConfigException('"' . get_class($this) . '::handler" must implement the SessionHandlerInterface.');
}
YII_DEBUG ? session_set_save_handler($this->handler, false) : @session_set_save_handler($this->handler, false);
} elseif ($this->getUseCustomStorage()) {
if (YII_DEBUG) {
session_set_save_handler(
[$this, 'openSession'],
[$this, 'closeSession'],
[$this, 'readSession'],
[$this, 'writeSession'],
[$this, 'destroySession'],
[$this, 'gcSession']
);
} else {
@session_set_save_handler(
[$this, 'openSession'],
[$this, 'closeSession'],
[$this, 'readSession'],
[$this, 'writeSession'],
[$this, 'destroySession'],
[$this, 'gcSession']
);
}
} elseif (
$sessionModuleName !== static::$_originalSessionModule
&& static::$_originalSessionModule !== null
&& static::$_originalSessionModule !== 'user'
) {
session_module_name(static::$_originalSessionModule);
}
}
定義於: yii\web\Session::remove()
移除 session 變數。
public mixed remove ( $key ) | ||
$key | string |
要移除的 session 變數名稱 |
return | mixed |
移除的值;如果沒有此 session 變數,則為 null。 |
---|
public function remove($key)
{
$this->open();
if (isset($_SESSION[$key])) {
$value = $_SESSION[$key];
unset($_SESSION[$key]);
return $value;
}
return null;
}
定義於: yii\web\Session::removeAll()
移除所有 session 變數。
public void removeAll ( ) |
public function removeAll()
{
$this->open();
foreach (array_keys($_SESSION) as $key) {
unset($_SESSION[$key]);
}
}
定義於: yii\web\Session::removeAllFlashes()
移除所有快閃訊息。
請注意,快閃訊息和一般的 session 變數共用相同的命名空間。如果您有一個使用相同名稱的普通 session 變數,它將會被此方法移除。
另請參閱
public void removeAllFlashes ( ) |
public function removeAllFlashes()
{
$counters = $this->get($this->flashParam, []);
foreach (array_keys($counters) as $key) {
unset($_SESSION[$key]);
}
unset($_SESSION[$this->flashParam]);
}
public mixed removeFlash ( $key ) | ||
$key | string |
識別快閃訊息的鍵。請注意,快閃訊息和一般的 session 變數共用相同的命名空間。如果您有一個使用相同名稱的普通 session 變數,它將會被此方法移除。 |
return | mixed |
移除的快閃訊息。如果快閃訊息不存在,則為 Null。 |
---|
public function removeFlash($key)
{
$counters = $this->get($this->flashParam, []);
$value = isset($_SESSION[$key], $counters[$key]) ? $_SESSION[$key] : null;
unset($counters[$key], $_SESSION[$key]);
$_SESSION[$this->flashParam] = $counters;
return $value;
}
public void set ( $key, $value ) | ||
$key | string |
Session 變數名稱 |
$value | mixed |
Session 變數值 |
public function set($key, $value)
{
$this->open();
$_SESSION[$key] = $value;
}
定義於: yii\web\Session::setCacheLimiter()
設定快取限制器
public void setCacheLimiter ( $cacheLimiter ) | ||
$cacheLimiter | string |
public function setCacheLimiter($cacheLimiter)
{
$this->freeze();
session_cache_limiter($cacheLimiter);
$this->unfreeze();
}
定義於: yii\web\Session::setCookieParams()
設定 session Cookie 參數。
傳遞給此方法的 cookie 參數將與 session_get_cookie_params()
的結果合併。
另請參閱 https://php.dev.org.tw/manual/en/function.session-set-cookie-params.php。
public array $value ) | ||
$value | array |
Cookie 參數,有效的鍵包含:
] |
throws | yii\base\InvalidArgumentException |
如果參數不完整。 |
---|
public function setCookieParams(array $value)
{
$this->_cookieParams = $value;
}
定義於: yii\web\Session::setFlash()
設定快閃訊息。
快閃訊息將會在請求中被存取後自動刪除,並且刪除將會在下一個請求中發生。如果已經有一個具有相同鍵的快閃訊息,它將會被新的訊息覆寫。
另請參閱
public void setFlash ( $key, $value = true, $removeAfterAccess = true ) | ||
$key | string |
識別快閃訊息的鍵。請注意,快閃訊息和一般的 session 變數共用相同的命名空間。如果您有一個使用相同名稱的普通 session 變數,其值將會被此方法覆寫。 |
$value | mixed |
快閃訊息 |
$removeAfterAccess | boolean |
快閃訊息是否應僅在被存取後才自動移除。如果為 false,快閃訊息將在下一個請求後自動移除,無論是否被存取。如果為 true(預設值),快閃訊息將保留到被存取之後。 |
public function setFlash($key, $value = true, $removeAfterAccess = true)
{
$counters = $this->get($this->flashParam, []);
$counters[$key] = $removeAfterAccess ? -1 : 0;
$_SESSION[$key] = $value;
$_SESSION[$this->flashParam] = $counters;
}
public void setGCProbability ( $value ) | ||
$value | float |
每次 session 初始化時啟動 GC (垃圾回收) 程序的機率 (百分比)。 |
throws | yii\base\InvalidArgumentException |
如果值不在 0 到 100 之間。 |
---|
public function setGCProbability($value)
{
$this->freeze();
if ($value >= 0 && $value <= 100) {
// percent * 21474837 / 2147483647 ≈ percent * 0.01
ini_set('session.gc_probability', floor($value * 21474836.47));
ini_set('session.gc_divisor', 2147483647);
} else {
throw new InvalidArgumentException('GCProbability must be a value between 0 and 100.');
}
$this->unfreeze();
}
定義於: yii\web\Session::setHasSessionId()
設定一個值,指示目前請求是否已傳送 session ID。
提供此方法是為了讓您可以覆寫判斷 session ID 是否已傳送的預設方式。
public void setHasSessionId ( $value ) | ||
$value | boolean |
目前請求是否已傳送 session ID。 |
public function setHasSessionId($value)
{
$this->_hasSessionId = $value;
}
public void setId ( $value ) | ||
$value | string |
當前 session 的 session ID |
public function setId($value)
{
session_id($value);
}
public void setName ( $value ) | ||
$value | string |
當前 session 的 session 名稱,必須是字母數字字串。預設為 "PHPSESSID"。 |
public function setName($value)
{
$this->freeze();
session_name($value);
$this->unfreeze();
}
public void setSavePath ( $value ) | ||
$value | string |
當前 session 的儲存路徑。這可以是目錄名稱或 路徑別名。 |
throws | yii\base\InvalidArgumentException |
如果路徑不是有效的目錄 |
---|
public function setSavePath($value)
{
$path = Yii::getAlias($value);
if (is_dir($path)) {
session_save_path($path);
} else {
throw new InvalidArgumentException("Session save path is not a valid directory: $value");
}
}
public void setTimeout ( $value ) | ||
$value | integer |
資料被視為「垃圾」並被清除的秒數 |
public function setTimeout($value)
{
$this->freeze();
ini_set('session.gc_maxlifetime', $value);
$this->unfreeze();
}
定義於: yii\web\Session::setUseCookies()
設定一個值,指示是否應使用 Cookie 來儲存 session ID。
可能的三種狀態
- true:cookie 以及僅 cookie 將被用於儲存 session ID。
- false:cookie 將不會被用於儲存 session ID。
- null:如果可能,cookie 將被用於儲存 session ID;如果不是,將會使用其他機制 (例如 GET 參數)
public void setUseCookies ( $value ) | ||
$value | boolean|null |
指示是否應使用 cookies 儲存 session ID 的值。 |
public function setUseCookies($value)
{
$this->freeze();
if ($value === false) {
ini_set('session.use_cookies', '0');
ini_set('session.use_only_cookies', '0');
} elseif ($value === true) {
ini_set('session.use_cookies', '1');
ini_set('session.use_only_cookies', '1');
} else {
ini_set('session.use_cookies', '1');
ini_set('session.use_only_cookies', '0');
}
$this->unfreeze();
}
定義於: yii\web\Session::setUseStrictMode()
另請參閱 https://php.dev.org.tw/manual/en/session.configuration.php#ini.session.use-strict-mode。
public void setUseStrictMode ( $value ) | ||
$value | boolean |
是否啟用嚴格模式。當為 |
public function setUseStrictMode($value)
{
if (PHP_VERSION_ID < 50502) {
if ($this->getUseCustomStorage() || !$value) {
self::$_useStrictModePolyfill = $value;
} else {
throw new InvalidConfigException('Enabling `useStrictMode` on PHP < 5.5.2 is only supported with custom storage classes.');
}
} else {
$this->freeze();
ini_set('session.use_strict_mode', $value ? '1' : '0');
$this->unfreeze();
}
}
public void setUseTransparentSessionID ( $value ) | ||
$value | boolean |
是否啟用透明 sid 支援。 |
public function setUseTransparentSessionID($value)
{
$this->freeze();
ini_set('session.use_trans_sid', $value ? '1' : '0');
$this->unfreeze();
}
public void trigger ( $name, yii\base\Event $event = null ) | ||
$name | string |
事件名稱 |
$event | yii\base\Event|null |
事件實例。如果未設定,將會建立預設的 yii\base\Event 物件。 |
public function trigger($name, Event $event = null)
{
$this->ensureBehaviors();
$eventHandlers = [];
foreach ($this->_eventWildcards as $wildcard => $handlers) {
if (StringHelper::matchWildcard($wildcard, $name)) {
$eventHandlers[] = $handlers;
}
}
if (!empty($this->_events[$name])) {
$eventHandlers[] = $this->_events[$name];
}
if (!empty($eventHandlers)) {
$eventHandlers = call_user_func_array('array_merge', $eventHandlers);
if ($event === null) {
$event = new Event();
}
if ($event->sender === null) {
$event->sender = $this;
}
$event->handled = false;
$event->name = $name;
foreach ($eventHandlers as $handler) {
$event->data = $handler[1];
call_user_func($handler[0], $event);
// stop further handling if the event is handled
if ($event->handled) {
return;
}
}
}
// invoke class-level attached handlers
Event::trigger($this, $name, $event);
}
方法在將 $fields 傳遞給 PDO 之前進行型別轉換。
預設實作將欄位 data
轉換為 \PDO::PARAM_LOB
。如果您需要特殊的型別轉換,您可以覆寫此方法。
protected array typecastFields ( $fields ) | ||
$fields | array |
將會傳遞給 PDO 的欄位。鍵 - 名稱,值 - 值 |
protected function typecastFields($fields)
{
if (isset($fields['data']) && !is_array($fields['data']) && !is_object($fields['data'])) {
$fields['data'] = new PdoValue($fields['data'], \PDO::PARAM_LOB);
}
return $fields;
}
定義於: yii\web\Session::unfreeze()
啟動 session 並從暫時變數還原資料。
protected void unfreeze ( ) |
protected function unfreeze()
{
if (null !== $this->_frozenSessionData) {
YII_DEBUG ? session_start() : @session_start();
if ($this->getIsActive()) {
Yii::info('Session unfrozen', __METHOD__);
} else {
$error = error_get_last();
$message = isset($error['message']) ? $error['message'] : 'Failed to unfreeze session.';
Yii::error($message, __METHOD__);
}
$_SESSION = $this->_frozenSessionData;
$this->_frozenSessionData = null;
}
}
protected void updateFlashCounters ( ) |
protected function updateFlashCounters()
{
$counters = $this->get($this->flashParam, []);
if (is_array($counters)) {
foreach ($counters as $key => $count) {
if ($count > 0) {
unset($counters[$key], $_SESSION[$key]);
} elseif ($count == 0) {
$counters[$key]++;
}
}
$_SESSION[$this->flashParam] = $counters;
} else {
// fix the unexpected problem that flashParam doesn't return an array
unset($_SESSION[$this->flashParam]);
}
}
註冊 或 登入 以發表評論。