0 追蹤者

抽象類別 yii\web\MultiFieldSession

繼承關係yii\web\MultiFieldSession » yii\web\Session » yii\base\Component » yii\base\BaseObject
實作介面ArrayAccessCountableIteratorAggregateyii\base\Configurable
子類別yii\web\DbSession
自版本起可用2.0.6
原始碼 https://github.com/yiisoft/yii2/blob/master/framework/web/MultiFieldSession.php

MultiFieldSession 是支援多欄位資料儲存實作的 Session 儲存基底類別。

使用多欄位資料儲存,Session 資料可以分散在儲存記錄的數個欄位中。使用這種儲存方式允許將特定的 Session 資料儲存到獨立的欄位中,然後可以用於以純 PHP 不允許的方式操作 Session。

例如,已驗證使用者的 ID 可以儲存為 MySQL 'session' 表格中的獨立欄位,這樣就可以查詢特定使用者的所有活動 Session,或隨時終止它們。

Session 寫入的客製化是透過 $writeCallback 執行,讀取是透過 $readCallback 執行。

在擴展此類別時,您應該使用 composeFields() 方法(在將 Session 資料寫入儲存空間時)和 extractData() 方法(在從儲存空間讀取 Session 資料時)。

公開屬性

隱藏繼承的屬性

屬性 類型 描述 定義於
$_forceRegenerateId string|null 如果啟用 useStrictMode 且 Session ID 需要重新產生,則保存 Session ID yii\web\Session
$_originalSessionModule string|null 保存原始 Session 模組(在註冊自訂處理器之前),以便在使用沒有自訂處理器的 Session 組件時,可以在具有自訂處理器的組件之後還原它。 yii\web\Session
$allFlashes array 快閃訊息 (key => message 或 key => [message1, message2])。 yii\web\Session
$behaviors yii\base\Behavior[] 附加到此組件的行為列表。 yii\base\Component
$cacheLimiter string 目前的快取限制器。 yii\web\Session
$cookieParams array Session Cookie 參數。 yii\web\Session
$count integer Session 變數的數量。 yii\web\Session
$flash string 識別快閃訊息的鍵。 yii\web\Session
$flashParam string 儲存快閃訊息資料的 Session 變數名稱。 yii\web\Session
$gCProbability float 每次 Session 初始化時啟動 GC(垃圾回收)程序的機率(百分比)。 yii\web\Session
$handler SessionHandlerInterface|array 實作 SessionHandlerInterface 的物件或組態陣列。 yii\web\Session
$hasSessionId boolean 目前請求是否已發送 Session ID。 yii\web\Session
$id string 目前的 Session ID。 yii\web\Session
$isActive boolean 工作階段是否已啟動。 yii\web\Session
$iterator yii\web\SessionIterator 用於遍歷工作階段變數的迭代器。 yii\web\Session
$name string 目前工作階段的名稱。 yii\web\Session
$readCallback callable 在工作階段資料讀取期間將被呼叫的回呼函數。 yii\web\MultiFieldSession
$savePath string 目前工作階段的儲存路徑,預設為 '/tmp'。 yii\web\Session
$timeout integer 資料在被視為「垃圾」並清除之前的秒數。 yii\web\Session
$useCookies boolean|null 指示是否應使用 Cookie 儲存工作階段 ID 的值。 yii\web\Session
$useCustomStorage boolean 是否使用自訂儲存空間。 yii\web\MultiFieldSession
$useStrictMode boolean 是否啟用嚴格模式。 yii\web\Session
$useTransparentSessionID boolean 是否啟用透明 sid 支援,預設為 false。 yii\web\Session
$writeCallback callable 在工作階段資料寫入期間將被呼叫的回呼函數。 yii\web\MultiFieldSession

受保護的屬性

隱藏繼承的屬性

屬性 類型 描述 定義於

公共方法

隱藏繼承的方法

方法 描述 定義於
__call() 呼叫非類別方法的具名方法。 yii\base\Component
__clone() 在透過複製現有物件建立物件後,會呼叫此方法。 yii\base\Component
__construct() 建構子。 yii\base\BaseObject
__get() 傳回元件屬性的值。 yii\base\Component
__isset() 檢查屬性是否已設定,即已定義且非 null。 yii\base\Component
__set() 設定元件屬性的值。 yii\base\Component
__unset() 將元件屬性設定為 null。 yii\base\Component
addFlash() 新增快閃訊息。 yii\web\Session
attachBehavior() 將行為附加到此元件。 yii\base\Component
attachBehaviors() 將行為清單附加到元件。 yii\base\Component
behaviors() 傳回此元件應表現為的行為清單。 yii\base\Component
canGetProperty() 傳回指示屬性是否可讀取的值。 yii\base\Component
canSetProperty() 傳回指示屬性是否可設定的值。 yii\base\Component
className() 傳回此類別的完整限定名稱。 yii\base\BaseObject
close() 結束目前的工作階段並儲存工作階段資料。 yii\web\Session
count() 傳回工作階段中的項目數量。 yii\web\Session
destroy() 釋放所有工作階段變數並銷毀所有已註冊到工作階段的資料。 yii\web\Session
detachBehavior() 從元件分離行為。 yii\base\Component
detachBehaviors() 從元件分離所有行為。 yii\base\Component
ensureBehaviors() 確保在 behaviors() 中宣告的行為已附加到此元件。 yii\base\Component
get() 傳回具有工作階段變數名稱的工作階段變數值。 yii\web\Session
getAllFlashes() 傳回所有快閃訊息。 yii\web\Session
getBehavior() 傳回具名行為物件。 yii\base\Component
getBehaviors() 傳回附加到此元件的所有行為。 yii\base\Component
getCacheLimiter() 傳回目前快取限制器 yii\web\Session
getCookieParams() yii\web\Session
getCount() 傳回工作階段中的項目數量。 yii\web\Session
getFlash() 傳回快閃訊息。 yii\web\Session
getGCProbability() yii\web\Session
getHasSessionId() 傳回指示目前請求是否已傳送工作階段 ID 的值。 yii\web\Session
getId() 取得工作階段 ID。 yii\web\Session
getIsActive() yii\web\Session
getIterator() 傳回用於遍歷工作階段變數的迭代器。 yii\web\Session
getName() 取得目前工作階段的名稱。 yii\web\Session
getSavePath() 取得目前工作階段的儲存路徑。 yii\web\Session
getTimeout() yii\web\Session
getUseCookies() 傳回指示是否應使用 Cookie 儲存工作階段 ID 的值。 yii\web\Session
getUseCustomStorage() 傳回指示是否使用自訂工作階段儲存空間的值。 yii\web\MultiFieldSession
getUseStrictMode() yii\web\Session
getUseTransparentSessionID() yii\web\Session
has() yii\web\Session
hasEventHandlers() 傳回指示是否有任何處理常式附加到具名事件的值。 yii\base\Component
hasFlash() 傳回指示是否有與指定索引鍵相關聯的快閃訊息的值。 yii\web\Session
hasMethod() 傳回指示是否已定義方法的值。 yii\base\Component
hasProperty() 傳回指示是否已為此元件定義屬性的值。 yii\base\Component
init() 初始化應用程式元件。 yii\web\Session
off() 從此元件分離現有的事件處理常式。 yii\base\Component
offsetExists() 介面 ArrayAccess 需要此方法。 yii\web\Session
offsetGet() 介面 ArrayAccess 需要此方法。 yii\web\Session
offsetSet() 介面 ArrayAccess 需要此方法。 yii\web\Session
offsetUnset() 介面 ArrayAccess 需要此方法。 yii\web\Session
on() 將事件處理常式附加到事件。 yii\base\Component
open() 啟動工作階段。 yii\web\Session
regenerateID() 使用新產生的一個 ID 更新目前的工作階段 ID。 yii\web\Session
remove() 移除工作階段變數。 yii\web\Session
removeAll() 移除所有工作階段變數。 yii\web\Session
removeAllFlashes() 移除所有快閃訊息。 yii\web\Session
removeFlash() 移除快閃訊息。 yii\web\Session
set() 新增工作階段變數。 yii\web\Session
setCacheLimiter() 設定快取限制器 yii\web\Session
setCookieParams() 設定工作階段 Cookie 參數。 yii\web\Session
setFlash() 設定快閃訊息。 yii\web\Session
setGCProbability() yii\web\Session
setHasSessionId() 設定指示目前請求是否已傳送工作階段 ID 的值。 yii\web\Session
setId() 設定工作階段 ID。 yii\web\Session
setName() 設定目前工作階段的名稱。 yii\web\Session
setSavePath() 設定目前工作階段的儲存路徑。 yii\web\Session
setTimeout() yii\web\Session
setUseCookies() 設定指示是否應使用 Cookie 儲存工作階段 ID 的值。 yii\web\Session
setUseStrictMode() yii\web\Session
setUseTransparentSessionID() yii\web\Session
trigger() 觸發事件。 yii\base\Component

受保護的方法

隱藏繼承的方法

方法 描述 定義於
composeFields() 組合用於工作階段寫入的儲存欄位集。 yii\web\MultiFieldSession
extractData() 從儲存欄位集中擷取工作階段資料。 yii\web\MultiFieldSession
freeze() 如果工作階段已啟動,則無法編輯工作階段 ini 設定。在 PHP 7.2+ 中,這會擲回例外。 yii\web\Session
registerSessionHandler() 註冊工作階段處理常式。 yii\web\Session
unfreeze() 啟動工作階段並從暫存變數還原資料 yii\web\Session
updateFlashCounters() 更新快閃訊息的計數器並移除過期的快閃訊息。 yii\web\Session

屬性詳細資訊

隱藏繼承的屬性

$readCallback 公開屬性

在工作階段資料讀取期間將被呼叫的回呼函數。回呼函數的簽章應如下所示

function ($fields)

其中 $fields 是用於讀取工作階段的儲存欄位集,而 $session 是此工作階段實例。如果回呼函數傳回陣列,則會將其合併到工作階段資料中。

例如

function ($fields) {
    return [
        'expireDate' => Yii::$app->formatter->asDate($fields['expire']),
    ];
}
public callable $readCallback null
$useCustomStorage 公開屬性

是否使用自訂儲存空間。

public boolean $useCustomStorage null
$writeCallback 公開屬性

在工作階段資料寫入期間將被呼叫的回呼函數。回呼函數的簽章應如下所示

function ($session)

其中 $session 是此工作階段實例,此變數可用於擷取工作階段資料。回呼函數應傳回實際的欄位集,這些欄位集應儲存到工作階段儲存空間中。

例如

function ($session) {
    return [
        'user_id' => Yii::$app->user->id,
        'ip' => $_SERVER['REMOTE_ADDR'],
        'is_trusted' => $session->get('is_trusted', false),
    ];
}
public callable $writeCallback null

方法詳細資訊

隱藏繼承的方法

__call() 公開方法

定義於: 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()");
}

            
__clone() 公開方法

定義於: yii\base\Component::__clone()

在透過複製現有物件建立物件後,會呼叫此方法。

它會移除所有行為,因為它們附加到舊物件。

public void __clone ( )

                public function __clone()
{
    $this->_events = [];
    $this->_eventWildcards = [];
    $this->_behaviors = null;
}

            
__construct() 公開方法

定義於: 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();
}

            
__get() 公開方法

定義於: 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);
}

            
__isset() 公開方法

定義於: yii\base\Component::__isset()

檢查屬性是否已設定,即已定義且非 null。

此方法將依下列順序檢查並採取相應動作

  • setter 定義的屬性:傳回屬性是否已設定
  • 行為的屬性:傳回屬性是否已設定
  • 針對不存在的屬性傳回 false

請勿直接呼叫此方法,因為它是 PHP 魔術方法,當執行 isset($component->property) 時,將會隱含地呼叫它。

另請參閱 https://php.dev.org.tw/manual/en/function.isset.php

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;
}

            
__set() 公開方法

定義於: 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);
}

            
__unset() 公開方法

定義於: yii\base\Component::__unset()

將元件屬性設定為 null。

此方法將依下列順序檢查並採取相應動作

  • setter 定義的屬性:將屬性值設定為 null
  • 行為的屬性:將屬性值設定為 null

請勿直接呼叫此方法,因為它是 PHP 魔術方法,當執行 unset($component->property) 時,將會隱含地呼叫它。

另請參閱 https://php.dev.org.tw/manual/en/function.unset.php

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);
}

            
addFlash() 公開方法

定義於: yii\web\Session::addFlash()

新增快閃訊息。

如果存在具有相同索引鍵的快閃訊息,則新的快閃訊息將附加到現有的訊息陣列。

另請參閱

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];
    }
}

            
attachBehavior() 公開方法

定義於: 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);
}

            
attachBehaviors() 公開方法

定義於: 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);
    }
}

            
behaviors() 公開方法

定義於: 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 [];
}

            
canGetProperty() 公開方法

定義於: 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;
}

            
canSetProperty() 公開方法

定義於: 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;
}

            
className() 公開靜態方法
自 2.0.14 版起已棄用。在 PHP >=5.5 上,請改用 ::class

定義於: yii\base\BaseObject::className()

傳回此類別的完整限定名稱。

public static string className ( )
return string

此類別的完整限定名稱。

                public static function className()
{
    return get_called_class();
}

            
close() 公開方法

定義於: yii\web\Session::close()

結束目前的工作階段並儲存工作階段資料。

public void close ( )

                public function close()
{
    if ($this->getIsActive()) {
        YII_DEBUG ? session_write_close() : @session_write_close();
    }
    $this->_forceRegenerateId = null;
}

            
composeFields() 受保護的方法

組合用於工作階段寫入的儲存欄位集。

protected array composeFields ( $id null, $data null )
$id string|null

選用的工作階段 ID

$data string|null

選用的工作階段資料

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;
}

            
count() 公開方法

定義於: yii\web\Session::count()

傳回工作階段中的項目數量。

介面 Countable 需要此方法。

public integer count ( )
return integer

工作階段中的項目數量。

                #[\ReturnTypeWillChange]
public function count()
{
    return $this->getCount();
}

            
destroy() 公開方法

定義於: yii\web\Session::destroy()

釋放所有工作階段變數並銷毀所有已註冊到工作階段的資料。

當工作階段未 active 時,此方法無效。請務必在呼叫它之前呼叫 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);
    }
}

            
detachBehavior() 公開方法

定義於: yii\base\Component::detachBehavior()

從元件分離行為。

將會叫用行為的 yii\base\Behavior::detach() 方法。

public yii\base\Behavior|null detachBehavior ( $name )
$name string

行為的名稱。

return yii\base\Behavior|null

分離的行為。如果行為不存在,則為 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;
}

            
detachBehaviors() 公開方法

定義於: yii\base\Component::detachBehaviors()

從元件分離所有行為。

public void detachBehaviors ( )

                public function detachBehaviors()
{
    $this->ensureBehaviors();
    foreach ($this->_behaviors as $name => $behavior) {
        $this->detachBehavior($name);
    }
}

            
ensureBehaviors() 公開方法

定義於: 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);
        }
    }
}

            
extractData() 受保護的方法

從儲存欄位集中擷取工作階段資料。

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'] : '';
}

            
freeze() 受保護的方法 (自版本 2.0.14 起可用)

定義於: yii\web\Session::freeze()

如果工作階段已啟動,則無法編輯工作階段 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__);
    }
}

            
get() 公開方法

定義於: yii\web\Session::get()

傳回具有工作階段變數名稱的工作階段變數值。

如果 session 變數不存在,將會回傳 $defaultValue

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;
}

            
getAllFlashes() 公開方法

定義於: yii\web\Session::getAllFlashes()

傳回所有快閃訊息。

你可以使用此方法在 view 檔案中顯示所有快閃訊息

<?php
foreach (Yii::$app->session->getAllFlashes() as $key => $message) {
    echo '<div class="alert alert-' . $key . '">' . $message . '</div>';
} ?>

透過以上程式碼,你可以使用像是 bootstrap alert classes 例如 successinfodanger 作為快閃訊息的 key 來影響 div 的顏色。

注意,如果你使用 addFlash()$message 將會是一個陣列,你將需要調整以上程式碼。

另請參閱

public array getAllFlashes ( $delete false )
$delete boolean

是否在方法被呼叫後立即刪除快閃訊息。如果為 false,快閃訊息將會在下個請求中自動被刪除。

return array

快閃訊息 (key => message 或 key => [message1, message2])。

                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;
}

            
getBehavior() 公開方法

定義於: yii\base\Component::getBehavior()

傳回具名行為物件。

public yii\base\Behavior|null getBehavior ( $name )
$name string

行為名稱

return yii\base\Behavior|null

行為物件,或當行為不存在時為 null

                public function getBehavior($name)
{
    $this->ensureBehaviors();
    return isset($this->_behaviors[$name]) ? $this->_behaviors[$name] : null;
}

            
getBehaviors() 公開方法

定義於: yii\base\Component::getBehaviors()

傳回附加到此元件的所有行為。

public yii\base\Behavior[] getBehaviors ( )
return yii\base\Behavior[]

附加到此組件的行為列表

                public function getBehaviors()
{
    $this->ensureBehaviors();
    return $this->_behaviors;
}

            
getCacheLimiter() 公開方法 (自版本 2.0.14 起可用)

定義於: yii\web\Session::getCacheLimiter()

傳回目前快取限制器

public string getCacheLimiter ( )
return string

目前的快取限制器

                public function getCacheLimiter()
{
    return session_cache_limiter();
}

            
getCookieParams() 公開方法
public array getCookieParams ( )
return array

Session Cookie 參數。

                public function getCookieParams()
{
    return array_merge(session_get_cookie_params(), array_change_key_case($this->_cookieParams));
}

            
getCount() 公開方法

定義於: yii\web\Session::getCount()

傳回工作階段中的項目數量。

public integer getCount ( )
return integer

Session 變數的數量

                public function getCount()
{
    $this->open();
    return count($_SESSION);
}

            
getFlash() 公開方法
public mixed getFlash ( $key, $defaultValue null, $delete false )
$key string

識別快閃訊息的 key

$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;
}

            
getGCProbability() 公開方法
public float getGCProbability ( )
return float

每次 Session 初始化時啟動 GC(垃圾回收)程序的機率(百分比)。

                public function getGCProbability()
{
    return (float) (ini_get('session.gc_probability') / ini_get('session.gc_divisor') * 100);
}

            
getHasSessionId() 公開方法

定義於: yii\web\Session::getHasSessionId()

傳回指示目前請求是否已傳送工作階段 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;
}

            
getId() 公開方法

定義於: yii\web\Session::getId()

取得工作階段 ID。

這是 PHP session_id() 的包裝器。

public string getId ( )
return string

目前的 session ID

                public function getId()
{
    return session_id();
}

            
getIsActive() 公開方法
public boolean getIsActive ( )
return boolean

Session 是否已啟動

                public function getIsActive()
{
    return session_status() === PHP_SESSION_ACTIVE;
}

            
getIterator() 公開方法

定義於: yii\web\Session::getIterator()

傳回用於遍歷工作階段變數的迭代器。

此方法為介面 IteratorAggregate 所需。

public yii\web\SessionIterator getIterator ( )
return yii\web\SessionIterator

用於遍歷工作階段變數的迭代器。

                #[\ReturnTypeWillChange]
public function getIterator()
{
    $this->open();
    return new SessionIterator();
}

            
getName() 公開方法

定義於: yii\web\Session::getName()

取得目前工作階段的名稱。

這是 PHP session_name() 的包裝器。

public string getName ( )
return string

目前的 session 名稱

                public function getName()
{
    return session_name();
}

            
getSavePath() 公開方法

定義於: yii\web\Session::getSavePath()

取得目前工作階段的儲存路徑。

這是 PHP session_save_path() 的包裝器。

public string getSavePath ( )
return string

目前工作階段的儲存路徑,預設為 '/tmp'。

                public function getSavePath()
{
    return session_save_path();
}

            
getTimeout() 公開方法
public integer getTimeout ( )
return integer

資料被視為「垃圾」並被清除之前的秒數。預設值為 1440 秒(或是 php.ini 中 "session.gc_maxlifetime" 設定的值)。

                public function getTimeout()
{
    return (int) ini_get('session.gc_maxlifetime');
}

            
getUseCookies() 公開方法

定義於: yii\web\Session::getUseCookies()

傳回指示是否應使用 Cookie 儲存工作階段 ID 的值。

另請參閱 setUseCookies()

public boolean|null getUseCookies ( )
return boolean|null

指示是否應使用 Cookie 儲存工作階段 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;
}

            
getUseCustomStorage() 公開方法

傳回指示是否使用自訂工作階段儲存空間的值。

此方法覆寫了父類別的實作並且總是回傳 true。

public boolean getUseCustomStorage ( )
return boolean

是否使用自訂儲存空間。

                public function getUseCustomStorage()
{
    return true;
}

            
getUseStrictMode() 公開方法 (自版本 2.0.38 起可用)
public boolean getUseStrictMode ( )
return boolean

是否啟用嚴格模式。

                public function getUseStrictMode()
{
    if (PHP_VERSION_ID < 50502) {
        return self::$_useStrictModePolyfill;
    }
    return (bool)ini_get('session.use_strict_mode');
}

            
getUseTransparentSessionID() 公開方法
public boolean getUseTransparentSessionID ( )
return boolean

是否啟用透明 sid 支援,預設為 false。

                public function getUseTransparentSessionID()
{
    return ini_get('session.use_trans_sid') == 1;
}

            
has() 公開方法

定義於: yii\web\Session::has()

public boolean has ( $key )
$key mixed

Session 變數名稱

return boolean

是否存在具名的 session 變數。

                public function has($key)
{
    $this->open();
    return isset($_SESSION[$key]);
}

            
hasEventHandlers() 公開方法

定義於: 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);
}

            
hasFlash() 公開方法

定義於: yii\web\Session::hasFlash()

傳回指示是否有與指定索引鍵相關聯的快閃訊息的值。

public boolean hasFlash ( $key )
$key string

識別快閃訊息類型的 Key

return boolean

在指定的 key 下是否存在任何快閃訊息

                public function hasFlash($key)
{
    return $this->getFlash($key) !== null;
}

            
hasMethod() 公開方法

定義於: yii\base\Component::hasMethod()

傳回指示是否已定義方法的值。

如果符合以下條件,則方法被定義:

  • 類別具有指定名稱的方法
  • 附加的行為具有給定名稱的方法(當 $checkBehaviors 為 true 時)。
public boolean hasMethod ( $name, $checkBehaviors true )
$name string

屬性名稱

$checkBehaviors boolean

是否將行為的方法視為此組件的方法

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;
}

            
hasProperty() 公開方法

定義於: yii\base\Component::hasProperty()

傳回指示是否已為此元件定義屬性的值。

如果符合以下條件,則屬性被定義:

  • 類別具有與指定名稱關聯的 getter 或 setter 方法(在此情況下,屬性名稱不區分大小寫);
  • 類別具有具有指定名稱的成員變數(當 $checkVars 為 true 時);
  • 附加的行為具有給定名稱的屬性(當 $checkBehaviors 為 true 時)。

另請參閱

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);
}

            
init() 公開方法

定義於: yii\web\Session::init()

初始化應用程式元件。

此方法為 IApplicationComponent 所需,並由應用程式調用。

public void init ( )

                public function init()
{
    parent::init();
    register_shutdown_function([$this, 'close']);
    if ($this->getIsActive()) {
        Yii::warning('Session is already started', __METHOD__);
        $this->updateFlashCounters();
    }
}

            
off() 公開方法

定義於: 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;
}

            
offsetExists() 公有方法

定義於: yii\web\Session::offsetExists()

介面 ArrayAccess 需要此方法。

public boolean offsetExists ( $offset )
$offset integer|string

要檢查的偏移量

                #[\ReturnTypeWillChange]
public function offsetExists($offset)
{
    $this->open();
    return isset($_SESSION[$offset]);
}

            
offsetGet() 公有方法

定義於: 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;
}

            
offsetSet() 公有方法

定義於: 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;
}

            
offsetUnset() 公有方法

定義於: yii\web\Session::offsetUnset()

介面 ArrayAccess 需要此方法。

public void offsetUnset ( $offset )
$offset integer|string

要取消設定元素的偏移量

                #[\ReturnTypeWillChange]
public function offsetUnset($offset)
{
    $this->open();
    unset($_SESSION[$offset]);
}

            
on() 公有方法

定義於: yii\base\Component::on()

將事件處理常式附加到事件。

事件處理器必須是有效的 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]);
    }
}

            
open() 公有方法

定義於: yii\web\Session::open()

啟動工作階段。

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__);
    }
}

            
regenerateID() 公有方法

定義於: yii\web\Session::regenerateID()

使用新產生的一個 ID 更新目前的工作階段 ID。

請參閱 https://php.dev.org.tw/session_regenerate_id 以取得更多詳細資訊。

當工作階段未 active 時,此方法無效。請務必在呼叫它之前呼叫 open()

另請參閱

public void regenerateID ( $deleteOldSession false )
$deleteOldSession boolean

是否刪除舊的相關聯的 session 檔案。

                public function regenerateID($deleteOldSession = false)
{
    if ($this->getIsActive()) {
        // add @ to inhibit possible warning due to race condition
        // https://github.com/yiisoft/yii2/pull/1812
        if (YII_DEBUG && !headers_sent()) {
            session_regenerate_id($deleteOldSession);
        } else {
            @session_regenerate_id($deleteOldSession);
        }
    }
}

            
registerSessionHandler() protected method

定義於: yii\web\Session::registerSessionHandler()

註冊工作階段處理常式。

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);
    }
}

            
remove() 公有方法

定義於: yii\web\Session::remove()

移除工作階段變數。

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;
}

            
removeAll() 公有方法

定義於: yii\web\Session::removeAll()

移除所有工作階段變數。

public void removeAll ( )

                public function removeAll()
{
    $this->open();
    foreach (array_keys($_SESSION) as $key) {
        unset($_SESSION[$key]);
    }
}

            
removeAllFlashes() 公有方法

定義於: 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]);
}

            
removeFlash() 公有方法
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;
}

            
set() 公有方法

定義於: yii\web\Session::set()

新增工作階段變數。

如果指定的名稱已存在,則舊值將被覆寫。

public void set ( $key, $value )
$key string

Session 變數名稱

$value mixed

Session 變數值

                public function set($key, $value)
{
    $this->open();
    $_SESSION[$key] = $value;
}

            
setCacheLimiter() 公有方法 (自 2.0.14 版本起可用)

定義於: yii\web\Session::setCacheLimiter()

設定快取限制器

public void setCacheLimiter ( $cacheLimiter )
$cacheLimiter string

                public function setCacheLimiter($cacheLimiter)
{
    $this->freeze();
    session_cache_limiter($cacheLimiter);
    $this->unfreeze();
}

            
setCookieParams() 公有方法

定義於: yii\web\Session::setCookieParams()

設定工作階段 Cookie 參數。

傳遞給此方法的 cookie 參數將與 session_get_cookie_params() 的結果合併。

另請參閱 https://php.dev.org.tw/manual/en/function.session-set-cookie-params.php

public void setCookieParams ( array $value )
$value array

Cookie 參數,有效的鍵包括:lifetimepathdomainsecurehttponly。從 Yii 2.0.21 開始,也支援 sameSite。它需要 PHP 7.3.0 或更高版本。為了安全性,如果在使用不受支援的 PHP 版本時設定了 sameSite,將會拋出例外。若要在不同的 PHP 版本中使用此功能,請先檢查版本。例如: `php [

'sameSite' => PHP_VERSION_ID >= 70300 ? yii\web\Cookie::SAME_SITE_LAX : null,

] ` 請參閱 https://owasp.org/www-community/SameSite 以取得有關 sameSite 的更多資訊。

throws yii\base\InvalidArgumentException

如果參數不完整。

                public function setCookieParams(array $value)
{
    $this->_cookieParams = $value;
}

            
setFlash() 公有方法

定義於: 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;
}

            
setGCProbability() 公有方法
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();
}

            
setHasSessionId() 公有方法

定義於: yii\web\Session::setHasSessionId()

設定指示目前請求是否已傳送工作階段 ID 的值。

提供此方法是為了讓您可以覆寫決定是否已發送 session ID 的預設方式。

public void setHasSessionId ( $value )
$value boolean

目前請求是否已發送 Session ID。

                public function setHasSessionId($value)
{
    $this->_hasSessionId = $value;
}

            
setId() 公有方法

定義於: yii\web\Session::setId()

設定工作階段 ID。

這是 PHP session_id() 的包裝器。

public void setId ( $value )
$value string

當前 session 的 session ID

                public function setId($value)
{
    session_id($value);
}

            
setName() 公有方法

定義於: yii\web\Session::setName()

設定目前工作階段的名稱。

這是 PHP session_name() 的包裝器。

public void setName ( $value )
$value string

當前 session 的 session 名稱,必須是字母數字字串。預設為 "PHPSESSID"。

                public function setName($value)
{
    $this->freeze();
    session_name($value);
    $this->unfreeze();
}

            
setSavePath() 公有方法

定義於: yii\web\Session::setSavePath()

設定目前工作階段的儲存路徑。

這是 PHP session_save_path() 的包裝器。

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");
    }
}

            
setTimeout() 公有方法
public void setTimeout ( $value )
$value integer

資料將被視為「垃圾」並被清除的秒數

                public function setTimeout($value)
{
    $this->freeze();
    ini_set('session.gc_maxlifetime', $value);
    $this->unfreeze();
}

            
setUseCookies() 公有方法

定義於: yii\web\Session::setUseCookies()

設定指示是否應使用 Cookie 儲存工作階段 ID 的值。

可能的三種狀態

  • true:cookies 和僅 cookies 將用於儲存 session ID。
  • false:cookies 將不被用於儲存 session ID。
  • null:如果可能,cookies 將被用於儲存 session ID;如果不可能,將使用其他機制(例如 GET 參數)
public void setUseCookies ( $value )
$value boolean|null

指示是否應使用 Cookie 儲存工作階段 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();
}

            
setUseStrictMode() 公有方法 (自 2.0.38 版本起可用)
public void setUseStrictMode ( $value )
$value boolean

是否啟用嚴格模式。當為 true 時,此設定會阻止 session 組件使用未初始化的 session ID。注意:在 PHP < 5.5.2 上啟用 useStrictMode 僅在使用自訂儲存類別時才受支援。警告!雖然啟用嚴格模式對於安全 session 是強制性的,但 'session.use-strict-mode' 的預設值為 0

                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();
    }
}

            
setUseTransparentSessionID() 公有方法
public void setUseTransparentSessionID ( $value )
$value boolean

是否啟用透明 sid 支援。

                public function setUseTransparentSessionID($value)
{
    $this->freeze();
    ini_set('session.use_trans_sid', $value ? '1' : '0');
    $this->unfreeze();
}

            
trigger() 公有方法

定義於: yii\base\Component::trigger()

觸發事件。

此方法表示事件的發生。它會調用事件的所有附加處理器,包括類別層級的處理器。

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);
}

            
unfreeze() protected method (available since version 2.0.14)

定義於: yii\web\Session::unfreeze()

啟動工作階段並從暫存變數還原資料

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;
    }
}

            
updateFlashCounters() protected method

定義於: yii\web\Session::updateFlashCounters()

更新快閃訊息的計數器並移除過期的快閃訊息。

此方法應僅在 init() 中調用一次。

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]);
    }
}