0 關注者

類別 yii\web\CacheSession

繼承關係yii\web\CacheSession » yii\web\Session » yii\base\Component » yii\base\BaseObject
實作介面ArrayAccess, Countable, IteratorAggregate, yii\base\Configurable
起始版本2.0
原始碼 https://github.com/yiisoft/yii2/blob/master/framework/web/CacheSession.php

CacheSession 實作了一個使用快取作為儲存媒介的 Session 組件。

所使用的快取可以是任何快取應用程式組件。快取應用程式組件的 ID 是透過 $cache 指定,預設為 'cache'。

請注意,根據定義,快取儲存是揮發性的,這意味著儲存在其中的資料可能會被換出而遺失。因此,您必須確保此組件使用的快取不是揮發性的。如果您想使用資料庫作為儲存媒介,yii\web\DbSession 會是更好的選擇。

以下範例展示如何配置應用程式以使用 CacheSession:將以下內容添加到您的應用程式配置中的 components

'session' => [
    'class' => 'yii\web\CacheSession',
    // 'cache' => 'mycache',
]

公開屬性

隱藏繼承的屬性

屬性 類型 描述 定義於
$_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
$cache yii\caching\CacheInterface|array|string 快取物件或快取物件的應用程式組件 ID。 yii\web\CacheSession
$cacheLimiter string 目前的快取限制器。 yii\web\Session
$cookieParams array Session Cookie 參數。 yii\web\Session
$count integer Session 變數的數量。 yii\web\Session
$flash string 識別快閃訊息的 key。 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 Session 是否已啟動。 yii\web\Session
$iterator yii\web\SessionIterator 用於遍歷 session 變數的迭代器。 yii\web\Session
$name string 目前的 session 名稱。 yii\web\Session
$savePath string 目前的 session 儲存路徑,預設為 '/tmp'。 yii\web\Session
$timeout integer 資料被視為「垃圾」並清除之前的秒數。 yii\web\Session
$useCookies boolean|null 指示是否應使用 Cookie 儲存 session ID 的值。 yii\web\Session
$useCustomStorage boolean 是否使用自訂儲存空間。 yii\web\CacheSession
$useStrictMode boolean 是否啟用嚴格模式。 yii\web\Session
$useTransparentSessionID boolean 是否啟用透明 sid 支援,預設為 false。 yii\web\Session

受保護的屬性

隱藏繼承的屬性

屬性 類型 描述 定義於

公開方法

隱藏繼承的方法

方法 描述 定義於
__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() 結束目前的 session 並儲存 session 資料。 yii\web\Session
count() 傳回 session 中的項目數量。 yii\web\Session
destroy() 釋放所有 session 變數並銷毀所有註冊到 session 的資料。 yii\web\Session
detachBehavior() 從元件分離行為。 yii\base\Component
detachBehaviors() 從元件分離所有行為。 yii\base\Component
ensureBehaviors() 確保在 behaviors() 中宣告的行為已附加到此元件。 yii\base\Component
get() 傳回具有 session 變數名稱的 session 變數值。 yii\web\Session
getAllFlashes() 傳回所有快閃訊息。 yii\web\Session
getBehavior() 傳回具名行為物件。 yii\base\Component
getBehaviors() 傳回附加到此元件的所有行為。 yii\base\Component
getCacheLimiter() 傳回目前的快取限制器 yii\web\Session
getCookieParams() yii\web\Session
getCount() 傳回 session 中的項目數量。 yii\web\Session
getFlash() 傳回快閃訊息。 yii\web\Session
getGCProbability() yii\web\Session
getHasSessionId() 傳回值,指示目前的請求是否已傳送 session ID。 yii\web\Session
getId() 取得 session ID。 yii\web\Session
getIsActive() yii\web\Session
getIterator() 傳回用於遍歷 session 變數的迭代器。 yii\web\Session
getName() 取得目前 session 的名稱。 yii\web\Session
getSavePath() 取得目前的 session 儲存路徑。 yii\web\Session
getTimeout() yii\web\Session
getUseCookies() 傳回值,指示是否應使用 Cookie 儲存 session ID。 yii\web\Session
getUseCustomStorage() 傳回值,指示是否使用自訂 session 儲存空間。 yii\web\CacheSession
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\CacheSession
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() 啟動 session。 yii\web\Session
regenerateID() 使用新產生的 ID 更新目前的 session ID。 yii\web\Session
remove() 移除 session 變數。 yii\web\Session
removeAll() 移除所有 session 變數。 yii\web\Session
removeAllFlashes() 移除所有快閃訊息。 yii\web\Session
removeFlash() 移除快閃訊息。 yii\web\Session
set() 新增 session 變數。 yii\web\Session
setCacheLimiter() 設定快取限制器 yii\web\Session
setCookieParams() 設定 session Cookie 參數。 yii\web\Session
setFlash() 設定快閃訊息。 yii\web\Session
setGCProbability() yii\web\Session
setHasSessionId() 設定值,指示目前的請求是否已傳送 session ID。 yii\web\Session
setId() 設定 session ID。 yii\web\Session
setName() 設定目前 session 的名稱。 yii\web\Session
setSavePath() 設定目前的 session 儲存路徑。 yii\web\Session
setTimeout() yii\web\Session
setUseCookies() 設定值,指示是否應使用 Cookie 儲存 session ID。 yii\web\Session
setUseStrictMode() yii\web\Session
setUseTransparentSessionID() yii\web\Session
trigger() 觸發事件。 yii\base\Component

受保護的方法

隱藏繼承的方法

方法 描述 定義於
calculateKey() 產生用於在快取中儲存 session 資料的唯一索引鍵。 yii\web\CacheSession
freeze() 如果 session 已啟動,則無法編輯 session ini 設定。在 PHP 7.2+ 中,這會擲回例外狀況。 yii\web\Session
registerSessionHandler() 註冊 session 處理常式。 yii\web\Session
unfreeze() 啟動 session 並從暫時變數還原資料 yii\web\Session
updateFlashCounters() 更新快閃訊息的計數器,並移除過期的快閃訊息。 yii\web\Session

屬性詳細資料

隱藏繼承的屬性

$cache 公開屬性

快取物件或快取物件的應用程式元件 ID。session 資料將使用此快取物件儲存。

在建立 CacheSession 物件之後,如果您想要變更此屬性,則應僅將其指派給快取物件。

從 2.0.2 版開始,這也可以是用於建立物件的組態陣列。

$useCustomStorage 公開屬性

是否使用自訂儲存空間。

public boolean $useCustomStorage 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

識別快閃訊息的 key。

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

            
calculateKey() 受保護的方法

產生用於在快取中儲存 session 資料的唯一索引鍵。

protected mixed calculateKey ( $id )
$id string

Session 變數名稱

return mixed

與 session 變數名稱關聯的安全快取索引鍵

                protected function calculateKey($id)
{
    return [__CLASS__, $id];
}

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

結束目前的 session 並儲存 session 資料。

public void close ( )

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

            
count() 公開方法

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

傳回 session 中的項目數量。

此方法是 Countable 介面所要求的。

public integer count ( )
return integer

Session 中的項目數量。

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

            
destroy() 公開方法

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

釋放所有 session 變數並銷毀所有註冊到 session 的資料。

當 session 未 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() public method

定義於: 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() public method

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

從元件分離所有行為。

public void detachBehaviors ( )

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

            
ensureBehaviors() public method

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

            
freeze() protected method (available since version 2.0.14)

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

            
get() public method

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

傳回具有 session 變數名稱的 session 變數值。

如果 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() public method

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

傳回所有快閃訊息。

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

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

透過上述程式碼,您可以使用 bootstrap alert 類別,例如 successinfodanger 作為快閃訊息的鍵值,以影響 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() public method

定義於: 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() public method

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

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

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

附加到此組件的行為列表

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

            
getCacheLimiter() public method (available since version 2.0.14)

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

傳回目前的快取限制器

public string getCacheLimiter ( )
return string

目前的快取限制器

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

            
getCookieParams() public method
public array getCookieParams ( )
return array

Session Cookie 參數。

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

            
getCount() public method

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

傳回 session 中的項目數量。

public integer getCount ( )
return integer

Session 變數的數量

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

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

            
getGCProbability() public method
public float getGCProbability ( )
return float

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

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

            
getHasSessionId() public method

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

            
getId() public method

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

取得 session ID。

這是 PHP session_id() 的包裝器。

public string getId ( )
return string

目前的 session ID

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

            
getIsActive() public method
public boolean getIsActive ( )
return boolean

Session 是否已啟動

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

            
getIterator() public method

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

傳回用於遍歷 session 變數的迭代器。

此方法為介面 IteratorAggregate 所需。

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

用於遍歷 session 變數的迭代器。

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

            
getName() public method

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

取得目前 session 的名稱。

這是 PHP session_name() 的包裝器。

public string getName ( )
return string

目前的 session 名稱

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

            
getSavePath() public method

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

取得目前的 session 儲存路徑。

這是 PHP session_save_path() 的包裝器。

public string getSavePath ( )
return string

目前的 session 儲存路徑,預設為 '/tmp'。

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

            
getTimeout() public method
public integer getTimeout ( )
return integer

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

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

            
getUseCookies() public method

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

傳回值,指示是否應使用 Cookie 儲存 session ID。

另請參閱 setUseCookies()

public boolean|null getUseCookies ( )
return boolean|null

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

            
getUseCustomStorage() public method

傳回值,指示是否使用自訂 session 儲存空間。

此方法覆寫父類別的實作,且永遠回傳 true。

public boolean getUseCustomStorage ( )
return boolean

是否使用自訂儲存空間。

                public function getUseCustomStorage()
{
    return true;
}

            
getUseStrictMode() public method (available since version 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 method
public boolean getUseTransparentSessionID ( )
return boolean

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

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

            
has() public method

定義於: 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() public method

定義於: 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() public method

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

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

public boolean hasFlash ( $key )
$key string

識別快閃訊息類型的鍵值

return boolean

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

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

            
hasMethod() public method

定義於: 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() public method

定義於: 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() public method

初始化應用程式元件。

public void init ( )

                public function init()
{
    parent::init();
    $this->cache = Instance::ensure($this->cache, 'yii\caching\CacheInterface');
}

            
off() public method

定義於: 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() public method

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

介面 ArrayAccess 需要此方法。

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

要檢查的偏移量

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

            
offsetGet() public method

定義於: 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() public method

定義於: 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() public method

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

介面 ArrayAccess 需要此方法。

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

要取消設定元素的偏移量

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

            
on() public method

定義於: 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() public method

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

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

            
regenerateID() public method

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

使用新產生的 ID 更新目前的 session ID。

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

當 session 未 active 時,此方法無效。請務必在呼叫此方法之前先呼叫 open()

另請參閱

public void regenerateID ( $deleteOldSession false )
$deleteOldSession boolean

是否刪除舊的關聯工作階段檔案。

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

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

            
remove() public method

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

移除 session 變數。

public mixed remove ( $key )
$key string

要移除的工作階段變數名稱

return mixed

已移除的值;如果沒有此工作階段變數,則為 null。

                public function remove($key)
{
    $this->open();
    if (isset($_SESSION[$key])) {
        $value = $_SESSION[$key];
        unset($_SESSION[$key]);
        return $value;
    }
    return null;
}

            
removeAll() public method

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

移除所有 session 變數。

public void removeAll ( )

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

            
removeAllFlashes() public method

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

移除所有快閃訊息。

請注意,快閃訊息和一般工作階段變數共用相同的命名空間。如果您有名稱相同的一般工作階段變數,則會被此方法移除。

另請參閱

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 method
public mixed removeFlash ( $key )
$key string

識別快閃訊息的鍵。請注意,快閃訊息和一般工作階段變數共用相同的命名空間。如果您有名稱相同的一般工作階段變數,則會被此方法移除。

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() public method

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

新增 session 變數。

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

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

Session 變數名稱

$value mixed

工作階段變數值

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

            
setCacheLimiter() public method (自 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() public method

定義於: 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 參數,有效的鍵包括: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() public method

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

設定快閃訊息。

快閃訊息在請求中被存取後將自動刪除,刪除將在下一個請求中發生。如果已經存在具有相同鍵的快閃訊息,它將被新的訊息覆寫。

另請參閱

public void setFlash ( $key, $value true, $removeAfterAccess true )
$key string

識別快閃訊息的鍵。請注意,快閃訊息和一般工作階段變數共用相同的命名空間。如果您有名稱相同的一般工作階段變數,其值將被此方法覆寫。

$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 method
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() public method

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

設定值,指示目前的請求是否已傳送 session ID。

提供此方法是為了讓您可以覆寫判斷是否發送工作階段 ID 的預設方式。

public void setHasSessionId ( $value )
$value boolean

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

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

            
setId() public method

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

設定 session ID。

這是 PHP session_id() 的包裝器。

public void setId ( $value )
$value string

目前工作階段的工作階段 ID

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

            
setName() public method

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

設定目前 session 的名稱。

這是 PHP session_name() 的包裝器。

public void setName ( $value )
$value string

目前工作階段的工作階段名稱,必須是字母數字字串。預設為 "PHPSESSID"。

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

            
setSavePath() public method

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

設定目前的 session 儲存路徑。

這是 PHP session_save_path() 的包裝器。

public void setSavePath ( $value )
$value string

目前的工作階段儲存路徑。這可以是目錄名稱或路徑別名

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 method
public void setTimeout ( $value )
$value integer

資料在被視為「垃圾」並清除之前的秒數

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

            
setUseCookies() public method

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

設定值,指示是否應使用 Cookie 儲存 session ID。

可能的三種狀態

  • true:將僅使用 Cookie 來儲存工作階段 ID。
  • false:將不使用 Cookie 來儲存工作階段 ID。
  • null:如果可能,將使用 Cookie 來儲存工作階段 ID;否則,將使用其他機制(例如 GET 參數)
public void setUseCookies ( $value )
$value boolean|null

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

            
setUseStrictMode() public method (自 2.0.38 版本起可用)
public void setUseStrictMode ( $value )
$value boolean

是否啟用嚴格模式。當為 true 時,此設定可防止工作階段組件使用未初始化的工作階段 ID。注意:在 PHP < 5.5.2 上啟用 `useStrictMode` 僅在使用自訂儲存類別時才受支援。警告!雖然啟用嚴格模式對於安全的工作階段是強制性的,但 '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 method
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() public method

定義於: 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 (自 2.0.14 版本起可用)

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

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