0 關注者

類別 yii\web\User

繼承yii\web\User » yii\base\Component » yii\base\BaseObject
實作yii\base\Configurable
自版本起可用2.0
原始碼 https://github.com/yiisoft/yii2/blob/master/framework/web/User.php

User 類別是用於 user 應用程式組件,以管理使用者驗證狀態。

你可以使用 $isGuest 來判斷目前使用者是否為訪客。如果使用者是訪客,$identity 屬性將會回傳 null。否則,它將會是 yii\web\IdentityInterface 的實例。

你可以呼叫各種方法來變更使用者驗證狀態

  • login():設定指定的身份,並在 session 和 cookie 中記住驗證狀態;
  • logout():將使用者標記為訪客,並從 session 和 cookie 中清除相關資訊;
  • setIdentity():變更使用者身份,而不觸及 session 或 cookie (這最適合用於無狀態 RESTful API 實作)。

請注意,User 僅維護使用者驗證狀態。它不處理如何驗證使用者。如何驗證使用者的邏輯應該在實作 yii\web\IdentityInterface 的類別中完成。你也需要使用此類別的名稱設定 $identityClass

預設情況下,User 在 yii\web\Application 中配置為應用程式組件。你可以透過 Yii::$app->user 存取該實例。

你可以透過在你的應用程式配置中的 `components` 下新增一個陣列來修改其配置,如下列範例所示

'user' => [
    'identityClass' => 'app\models\User', // User must implement the IdentityInterface
    'enableAutoLogin' => true,
    // 'loginUrl' => ['user/login'],
    // ...
]

公開屬性

隱藏繼承的屬性

屬性 類型 描述 定義於
$absoluteAuthTimeout integer|null 使用者自動登出的秒數,無論是否有活動。 yii\web\User
$absoluteAuthTimeoutParam string 用於儲存已驗證狀態絕對到期時間戳記的 session 變數名稱。 yii\web\User
$acceptableRedirectTypes array 此元件應重新導向至 $loginUrl 的 MIME 類型。 yii\web\User
$accessChecker yii\rbac\CheckAccessInterface|string|array|null 用於檢查存取權限的存取檢查器物件,或存取檢查器的應用程式元件 ID。 yii\web\User
$authKeyParam string 用於儲存驗證金鑰的 session 變數名稱。 yii\web\User
$authTimeout integer|null 使用者保持非活動狀態時,自動登出的秒數。 yii\web\User
$authTimeoutParam string 用於儲存已驗證狀態到期時間戳記值的 session 變數名稱。 yii\web\User
$autoRenewCookie boolean 是否在每次請求頁面時自動更新身分 cookie。 yii\web\User
$behaviors yii\base\Behavior[] 附加到此元件的行為列表。 yii\base\Component
$enableAutoLogin boolean 是否啟用基於 cookie 的登入。 yii\web\User
$enableSession boolean 是否使用 session 來跨多個請求持久化驗證狀態。 yii\web\User
$id string|integer|null 使用者的唯一識別符。 yii\web\User
$idParam string 用於儲存 $id 值的 session 變數名稱。 yii\web\User
$identity yii\web\IdentityInterface|null 與目前已登入使用者關聯的身分物件。 yii\web\User
$identityClass string $identity 物件的類別名稱。 yii\web\User
$identityCookie array 身分 cookie 的組態。 yii\web\User
$isGuest boolean 目前使用者是否為訪客。 yii\web\User
$loginUrl string|array|null 當呼叫 loginRequired() 時的登入 URL。 yii\web\User
$returnUrl string 使用者登入後應重新導向的 URL。 yii\web\User
$returnUrlParam string 用於儲存 $returnUrl 值的 session 變數名稱。 yii\web\User

公開方法

隱藏繼承的方法

方法 描述 定義於
__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
attachBehavior() 將行為附加到此元件。 yii\base\Component
attachBehaviors() 將行為列表附加到元件。 yii\base\Component
behaviors() 傳回此元件應表現為的行為列表。 yii\base\Component
can() 檢查使用者是否可以執行給定權限指定的作業。 yii\web\User
canGetProperty() 傳回指示屬性是否可讀取的值。 yii\base\Component
canSetProperty() 傳回指示屬性是否可設定的值。 yii\base\Component
checkRedirectAcceptable() 檢查 Accept 標頭是否包含允許重新導向至登入頁面的內容類型。 yii\web\User
className() 傳回此類別的完整名稱。 yii\base\BaseObject
detachBehavior() 從元件中分離行為。 yii\base\Component
detachBehaviors() 從元件中分離所有行為。 yii\base\Component
ensureBehaviors() 確保在 behaviors() 中宣告的行為已附加到此元件。 yii\base\Component
getBehavior() 傳回具名行為物件。 yii\base\Component
getBehaviors() 傳回附加到此元件的所有行為。 yii\base\Component
getId() 傳回唯一代表使用者的值。 yii\web\User
getIdentity() 傳回與目前已登入使用者關聯的身分物件。 yii\web\User
getIsGuest() 傳回指示使用者是否為訪客(未驗證)的值。 yii\web\User
getReturnUrl() 傳回瀏覽器在成功登入後應重新導向到的 URL。 yii\web\User
hasEventHandlers() 傳回指示是否有名稱事件附加任何處理常式的值。 yii\base\Component
hasMethod() 傳回指示是否已定義方法的值。 yii\base\Component
hasProperty() 傳回指示是否為此元件定義屬性的值。 yii\base\Component
init() 初始化應用程式元件。 yii\web\User
login() 登入使用者。 yii\web\User
loginByAccessToken() 透過給定的存取權杖登入使用者。 yii\web\User
loginRequired() 將使用者瀏覽器重新導向至登入頁面。 yii\web\User
logout() 登出目前使用者。 yii\web\User
off() 從此元件分離現有的事件處理常式。 yii\base\Component
on() 將事件處理常式附加到事件。 yii\base\Component
setIdentity() 設定使用者身分物件。 yii\web\User
setReturnUrl() 將 URL 記住在 session 中,以便稍後可透過 getReturnUrl() 擷取回來。 yii\web\User
switchIdentity() 為目前使用者切換到新的身分。 yii\web\User
trigger() 觸發事件。 yii\base\Component

受保護的方法

隱藏繼承的方法

方法 描述 定義於
afterLogin() 在使用者成功登入後呼叫此方法。 yii\web\User
afterLogout() 在使用者透過 logout() 登出後立即呼叫此方法。 yii\web\User
beforeLogin() 在登入使用者之前呼叫此方法。 yii\web\User
beforeLogout() 在呼叫 logout() 以登出使用者時呼叫此方法。 yii\web\User
getAccessChecker() 傳回用於檢查存取權限的存取檢查器。 yii\web\User
getAuthManager() 傳回與使用者元件關聯的驗證管理器。 yii\web\User
getIdentityAndDurationFromCookie() 判斷身分 cookie 是否具有有效格式且包含有效驗證金鑰。 yii\web\User
loginByCookie() 透過 cookie 登入使用者。 yii\web\User
regenerateCsrfToken() 重新產生 CSRF 權杖 yii\web\User
removeIdentityCookie() 移除身分 cookie。 yii\web\User
renewAuthStatus() 使用來自 session 和 cookie 的資訊更新驗證狀態。 yii\web\User
renewIdentityCookie() 更新身分 cookie。 yii\web\User
sendIdentityCookie() 傳送身分 cookie。 yii\web\User

常數

隱藏繼承的常數

常數 描述 定義於
EVENT_AFTER_LOGIN 'afterLogin' yii\web\User
EVENT_AFTER_LOGOUT 'afterLogout' yii\web\User
EVENT_BEFORE_LOGIN 'beforeLogin' yii\web\User
EVENT_BEFORE_LOGOUT 'beforeLogout' yii\web\User

屬性詳細資訊

隱藏繼承的屬性

$absoluteAuthTimeout 公開屬性

使用者自動登出的秒數,無論是否有活動。請注意,如果 $enableAutoLogintrue,則此功能將無法運作。

$absoluteAuthTimeoutParam 公開屬性

用於儲存已驗證狀態絕對到期時間戳記值的 session 變數名稱。當設定 $absoluteAuthTimeout 時,會使用此變數。

public string $absoluteAuthTimeoutParam '__absoluteExpire'
$acceptableRedirectTypes 公開屬性 (自版本 2.0.8 起可用)

此元件應重新導向至 $loginUrl 的 MIME 類型。

public array $acceptableRedirectTypes = [
    
'text/html',
    
'application/xhtml+xml',
]
$accessChecker 公開屬性 (自版本 2.0.9 起可用)

用於檢查存取權限的存取檢查器物件,或存取檢查器的應用程式元件 ID。如果未設定,將會使用應用程式驗證管理器。

$authKeyParam 公開屬性 (自版本 2.0.41 起可用)

用於儲存驗證金鑰的 session 變數名稱。

public string $authKeyParam '__authKey'
$authTimeout 公開屬性

使用者保持非活動狀態時,自動登出的秒數。如果未設定此屬性,使用者將在目前 session 過期後登出 (請參閱 yii\web\Session::$timeout)。請注意,如果 $enableAutoLogintrue,則此功能將無法運作。

public integer|null $authTimeout null
$authTimeoutParam 公開屬性

用於儲存已驗證狀態到期時間戳記值的 session 變數名稱。當設定 $authTimeout 時,會使用此變數。

public string $authTimeoutParam '__expire'
$autoRenewCookie 公開屬性

是否在每次請求頁面時自動更新身分 cookie。此屬性僅在 $enableAutoLogintrue 時有效。當此值為 false 時,身分 cookie 將在使用者最初登入後指定的持續時間後過期。當此值為 true 時,身分 cookie 將在使用者上次造訪網站後指定的持續時間後過期。

另請參閱 $enableAutoLogin

public boolean $autoRenewCookie true
$enableAutoLogin 公開屬性

是否啟用基於 cookie 的登入。預設值為 false。請注意,如果 $enableSessionfalse,則會忽略此屬性。

public boolean $enableAutoLogin false
$enableSession 公開屬性

是否使用 session 來跨多個請求持久化驗證狀態。如果您的應用程式是無狀態的,您可以將此屬性設定為 false,這通常適用於 RESTful API。

public boolean $enableSession true
$id 公開屬性

使用者的唯一識別符。如果為 null,則表示使用者是訪客。

public string|integer|null $id null
$idParam 公開屬性

用於儲存 $id 值的 session 變數名稱。

public string $idParam '__id'
$identity 公開屬性

與目前已登入使用者關聯的身分物件。如果使用者未登入(未驗證),則傳回 null

$identityClass 公開屬性

$identity 物件的類別名稱。

public string $identityClass null
$identityCookie 公開屬性

身分 cookie 的組態。此屬性僅在 $enableAutoLogintrue 時使用。

另請參閱 yii\web\Cookie

public array $identityCookie = [
    
'name' => '_identity',
    
'httpOnly' => true,
]
$isGuest 公開屬性

目前使用者是否為訪客。

public boolean $isGuest null
$loginUrl 公開屬性

當呼叫 loginRequired() 時的登入 URL。如果給定陣列,將呼叫 yii\web\UrlManager::createUrl() 以建立對應的 URL。陣列的第一個元素應為登入動作的路徑,其餘的名稱-值組是用於建構登入 URL 的 GET 參數。例如,

['site/login', 'ref' => 1]

如果此屬性為 null,當呼叫 loginRequired() 時,將會引發 403 HTTP 例外。

public string|array|null $loginUrl = [
    
'site/login',
]
$returnUrl 公開屬性

使用者登入後應重新導向的 URL。請注意,此屬性的類型在 getter 和 setter 中有所不同。請參閱 getReturnUrl()setReturnUrl() 以取得詳細資訊。

public string $returnUrl null
$returnUrlParam 公開屬性

用於儲存 $returnUrl 值的 session 變數名稱。

public string $returnUrlParam '__returnUrl'

方法詳細資訊

隱藏繼承的方法

__call() 公開方法

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

呼叫非類別方法的具名方法。

此方法將檢查是否有任何附加的行為具有具名方法,並在可用時執行它。

請勿直接呼叫此方法,因為它是 PHP magic method,當呼叫不明方法時,將會隱含地呼叫它。

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 magic method,當執行 $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 magic method,當執行 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 magic method,當執行 $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() public method

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

            
afterLogin() protected method

在使用者成功登入後呼叫此方法。

預設實作將觸發 EVENT_AFTER_LOGIN 事件。如果您覆寫此方法,請確保您呼叫父類別的實作,以便事件可以被觸發。

protected void afterLogin ( $identity, $cookieBased, $duration )
$identity yii\web\IdentityInterface

使用者身分資訊

變數 $cookieBased boolean

登入是否基於 Cookie

變數 $duration integer

使用者保持登入狀態的秒數。如果為 0,則表示登入直到使用者關閉瀏覽器或手動銷毀 session 為止。

                protected function afterLogin($identity, $cookieBased, $duration)
{
    $this->trigger(self::EVENT_AFTER_LOGIN, new UserEvent([
        'identity' => $identity,
        'cookieBased' => $cookieBased,
        'duration' => $duration,
    ]));
}

            
afterLogout() protected method

在使用者透過 logout() 登出後立即呼叫此方法。

預設實作將觸發 EVENT_AFTER_LOGOUT 事件。如果您覆寫此方法,請確保您呼叫父類別的實作,以便事件可以被觸發。

protected void afterLogout ( $identity )
$identity yii\web\IdentityInterface

使用者身分資訊

                protected function afterLogout($identity)
{
    $this->trigger(self::EVENT_AFTER_LOGOUT, new UserEvent([
        'identity' => $identity,
    ]));
}

            
attachBehavior() public method

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

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

            
beforeLogin() protected method

在登入使用者之前呼叫此方法。

預設實作將觸發 EVENT_BEFORE_LOGIN 事件。如果您覆寫此方法,請確保您呼叫父類別的實作,以便事件可以被觸發。

protected boolean beforeLogin ( $identity, $cookieBased, $duration )
$identity yii\web\IdentityInterface

使用者身分資訊

變數 $cookieBased boolean

登入是否基於 Cookie

變數 $duration integer

使用者保持登入狀態的秒數。如果為 0,則表示登入直到使用者關閉瀏覽器或手動銷毀 session 為止。

return boolean

使用者是否應該繼續保持登入狀態

                protected function beforeLogin($identity, $cookieBased, $duration)
{
    $event = new UserEvent([
        'identity' => $identity,
        'cookieBased' => $cookieBased,
        'duration' => $duration,
    ]);
    $this->trigger(self::EVENT_BEFORE_LOGIN, $event);
    return $event->isValid;
}

            
beforeLogout() protected method

在呼叫 logout() 以登出使用者時呼叫此方法。

預設實作將觸發 EVENT_BEFORE_LOGOUT 事件。如果您覆寫此方法,請確保您呼叫父類別的實作,以便事件可以被觸發。

protected boolean beforeLogout ( $identity )
$identity yii\web\IdentityInterface

使用者身分資訊

return boolean

使用者是否應該繼續保持登出狀態

                protected function beforeLogout($identity)
{
    $event = new UserEvent([
        'identity' => $identity,
    ]);
    $this->trigger(self::EVENT_BEFORE_LOGOUT, $event);
    return $event->isValid;
}

            
behaviors() public method

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

            
can() public method

檢查使用者是否可以執行給定權限指定的作業。

請注意,您必須配置 "authManager" 應用程式元件才能使用此方法。否則它將始終返回 false。

public boolean can ( $permissionName, $params = [], $allowCaching true )
變數 $permissionName string

需要存取檢查的權限名稱(例如 "edit post")。

$params array

將傳遞給與分配給使用者的角色和權限相關聯的規則的名稱-值對。

變數 $allowCaching boolean

是否允許快取存取檢查的結果。當此參數為 true(預設值)時,如果之前執行過某個操作的存取檢查,則在呼叫此方法檢查相同操作時,將直接返回其結果。如果此參數為 false,則此方法將始終呼叫 yii\rbac\CheckAccessInterface::checkAccess() 以取得最新的存取結果。請注意,此快取僅在同一個請求中有效,並且僅在 $params = [] 時有效。

return boolean

使用者是否可以執行給定權限指定的操作。

                public function can($permissionName, $params = [], $allowCaching = true)
{
    if ($allowCaching && empty($params) && isset($this->_access[$permissionName])) {
        return $this->_access[$permissionName];
    }
    if (($accessChecker = $this->getAccessChecker()) === null) {
        return false;
    }
    $access = $accessChecker->checkAccess($this->getId(), $permissionName, $params);
    if ($allowCaching && empty($params)) {
        $this->_access[$permissionName] = $access;
    }
    return $access;
}

            
canGetProperty() public method

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

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

            
checkRedirectAcceptable() public method (自版本 2.0.8 起可用)

檢查 Accept 標頭是否包含允許重新導向至登入頁面的內容類型。

預設情況下,登入頁面假定服務 text/htmlapplication/xhtml+xml。您可以透過修改 $acceptableRedirectTypes 屬性來變更可接受的內容類型。

另請參閱 $acceptableRedirectTypes

public boolean checkRedirectAcceptable ( )
return boolean

此請求是否可以重定向到登入頁面。

                public function checkRedirectAcceptable()
{
    $acceptableTypes = Yii::$app->getRequest()->getAcceptableContentTypes();
    if (empty($acceptableTypes) || (count($acceptableTypes) === 1 && array_keys($acceptableTypes)[0] === '*/*')) {
        return true;
    }
    foreach ($acceptableTypes as $type => $params) {
        if (in_array($type, $this->acceptableRedirectTypes, true)) {
            return true;
        }
    }
    return false;
}

            
className() public static method
自 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();
}

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

            
getAccessChecker() protected method (自版本 2.0.9 起可用)

傳回用於檢查存取權限的存取檢查器。

protected yii\rbac\CheckAccessInterface getAccessChecker ( )

                protected function getAccessChecker()
{
    return $this->accessChecker !== null ? $this->accessChecker : $this->getAuthManager();
}

            
getAuthManager() protected method (自版本 2.0.6 起可用)
自版本 2.0.9 起已棄用,將在 2.1 中移除。請改用 getAccessChecker()

傳回與使用者元件關聯的驗證管理器。

預設情況下,這是 authManager 應用程式元件。如果需要,您可以覆寫此方法以返回不同的 auth manager 實例。

protected yii\rbac\ManagerInterface getAuthManager ( )

                protected function getAuthManager()
{
    return Yii::$app->getAuthManager();
}

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

            
getId() public method

傳回唯一代表使用者的值。

另請參閱 getIdentity()

public string|integer|null getId ( )
return string|integer|null

使用者的唯一識別符。如果為 null,則表示使用者是訪客。

                public function getId()
{
    $identity = $this->getIdentity();
    return $identity !== null ? $identity->getId() : null;
}

            
getIdentity() public method

傳回與目前已登入使用者關聯的身分物件。

$enableSession 為 true 時,如果之前尚未完成,此方法可能會嘗試讀取儲存在 session 中的使用者驗證資料,並重建對應的身分物件。

另請參閱

public yii\web\IdentityInterface|null getIdentity ( $autoRenew true )
變數 $autoRenew boolean

如果之前尚未完成自動續訂驗證狀態。這僅在 $enableSession 為 true 時有用。

return yii\web\IdentityInterface|null

與目前已登入使用者關聯的身分物件。如果使用者未登入(未驗證),則傳回 null

                public function getIdentity($autoRenew = true)
{
    if ($this->_identity === false) {
        if ($this->enableSession && $autoRenew) {
            try {
                $this->_identity = null;
                $this->renewAuthStatus();
            } catch (\Exception $e) {
                $this->_identity = false;
                throw $e;
            } catch (\Throwable $e) {
                $this->_identity = false;
                throw $e;
            }
        } else {
            return null;
        }
    }
    return $this->_identity;
}

            
getIdentityAndDurationFromCookie() protected method (自版本 2.0.9 起可用)

判斷身分 cookie 是否具有有效格式且包含有效驗證金鑰。

$enableAutoLogin 為 true 時,將使用此方法。此方法嘗試使用身分 Cookie 中的資訊驗證使用者。

另請參閱 loginByCookie()

protected array|null getIdentityAndDurationFromCookie ( )
return array|null

如果有效,則返回 'identity' 和 'duration' 的陣列,否則返回 null。

                protected function getIdentityAndDurationFromCookie()
{
    $value = Yii::$app->getRequest()->getCookies()->getValue($this->identityCookie['name']);
    if ($value === null) {
        return null;
    }
    $data = json_decode($value, true);
    if (is_array($data) && count($data) == 3) {
        list($id, $authKey, $duration) = $data;
        /* @var $class IdentityInterface */
        $class = $this->identityClass;
        $identity = $class::findIdentity($id);
        if ($identity !== null) {
            if (!$identity instanceof IdentityInterface) {
                throw new InvalidValueException("$class::findIdentity() must return an object implementing IdentityInterface.");
            } elseif (!$identity->validateAuthKey($authKey)) {
                $ip = Yii::$app->getRequest()->getUserIP();
                Yii::warning("Invalid cookie auth key attempted for user '$id' from $ip: $authKey", __METHOD__);
            } else {
                return ['identity' => $identity, 'duration' => $duration];
            }
        }
    }
    $this->removeIdentityCookie();
    return null;
}

            
getIsGuest() public method

傳回指示使用者是否為訪客(未驗證)的值。

另請參閱 getIdentity()

public boolean getIsGuest ( )
return boolean

目前使用者是否為訪客。

                public function getIsGuest()
{
    return $this->getIdentity() === null;
}

            
getReturnUrl() public method

傳回瀏覽器在成功登入後應重新導向到的 URL。

此方法從 session 讀取返回 URL。它通常被登入 action 使用,該 action 可能會呼叫此方法以將瀏覽器重新導向到成功驗證後應前往的位置。

另請參閱 loginRequired()

public string getReturnUrl ( $defaultUrl null )
$defaultUrl string|array|null

預設返回 URL,以防先前未設定。如果此值為 null 且先前未設定返回 URL,則將重新導向至 yii\web\Application::$homeUrl。關於 URL 的可接受格式,請參閱 setReturnUrl()

return string

使用者登入後應重新導向的 URL。

                public function getReturnUrl($defaultUrl = null)
{
    $url = Yii::$app->getSession()->get($this->returnUrlParam, $defaultUrl);
    if (is_array($url)) {
        if (isset($url[0])) {
            return Yii::$app->getUrlManager()->createUrl($url);
        }
        $url = null;
    }
    return $url === null ? Yii::$app->getHomeUrl() : $url;
}

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

            
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();
    if ($this->identityClass === null) {
        throw new InvalidConfigException('User::identityClass must be set.');
    }
    if ($this->enableAutoLogin && !isset($this->identityCookie['name'])) {
        throw new InvalidConfigException('User::identityCookie must contain the "name" element.');
    }
    if ($this->accessChecker !== null) {
        $this->accessChecker = Instance::ensure($this->accessChecker, '\yii\rbac\CheckAccessInterface');
    }
}

            
login() public method

登入使用者。

在使用者登入後

  • 使用者的身分資訊可從 $identity 屬性取得

如果 $enableSessiontrue

  • 身分資訊將儲存在 session 中,並在後續請求中可用
  • $duration == 0 的情況下:只要 session 保持活動狀態或直到使用者關閉瀏覽器
  • $duration > 0 的情況下:只要 session 保持活動狀態,或者只要 cookie 在 $enableAutoLogin 設定為 true 時,在其 $duration 秒數內保持有效。

如果 $enableSessionfalse

  • $duration 參數將被忽略
public boolean login ( yii\web\IdentityInterface $identity, $duration 0 )
$identity yii\web\IdentityInterface

使用者身分 (應已通過驗證)

變數 $duration integer

使用者可以保持登入狀態的秒數,預設為 0

return boolean

使用者是否已登入

                public function login(IdentityInterface $identity, $duration = 0)
{
    if ($this->beforeLogin($identity, false, $duration)) {
        $this->switchIdentity($identity, $duration);
        $id = $identity->getId();
        $ip = Yii::$app->getRequest()->getUserIP();
        if ($this->enableSession) {
            $log = "User '$id' logged in from $ip with duration $duration.";
        } else {
            $log = "User '$id' logged in from $ip. Session not enabled.";
        }
        $this->regenerateCsrfToken();
        Yii::info($log, __METHOD__);
        $this->afterLogin($identity, false, $duration);
    }
    return !$this->getIsGuest();
}

            
loginByAccessToken() public method

透過給定的存取權杖登入使用者。

此方法將首先通過調用 yii\web\IdentityInterface::findIdentityByAccessToken() 和提供的訪問令牌來驗證使用者。如果成功,它將調用 login() 以登入已驗證的使用者。如果驗證失敗或 login() 不成功,它將返回 null。

public yii\web\IdentityInterface|null loginByAccessToken ( $token, $type null )
$token string

訪問令牌

$type mixed

令牌的類型。此參數的值取決於實作。例如,yii\filters\auth\HttpBearerAuth 將此參數設定為 yii\filters\auth\HttpBearerAuth

return yii\web\IdentityInterface|null

與給定訪問令牌相關聯的身分。如果訪問令牌無效或 login() 不成功,則返回 Null。

                public function loginByAccessToken($token, $type = null)
{
    /* @var $class IdentityInterface */
    $class = $this->identityClass;
    $identity = $class::findIdentityByAccessToken($token, $type);
    if ($identity && $this->login($identity)) {
        return $identity;
    }
    return null;
}

            
loginByCookie() protected method

透過 cookie 登入使用者。

此方法嘗試使用 身分 cookie 提供的 ID 和 authKey 資訊登入使用者。

protected void loginByCookie ( )

                protected function loginByCookie()
{
    $data = $this->getIdentityAndDurationFromCookie();
    if (isset($data['identity'], $data['duration'])) {
        $identity = $data['identity'];
        $duration = $data['duration'];
        if ($this->beforeLogin($identity, true, $duration)) {
            $this->switchIdentity($identity, $this->autoRenewCookie ? $duration : 0);
            $id = $identity->getId();
            $ip = Yii::$app->getRequest()->getUserIP();
            Yii::info("User '$id' logged in from $ip via cookie.", __METHOD__);
            $this->afterLogin($identity, true, $duration);
        }
    }
}

            
loginRequired() public method

將使用者瀏覽器重新導向至登入頁面。

在重新導向前,目前的 URL (如果不是 AJAX url) 將保留為 $returnUrl,以便使用者瀏覽器在成功登入後可以重新導向回目前頁面。

請確保設定 $loginUrl,以便在調用此方法後,使用者瀏覽器可以重新導向到指定的登入 URL。

請注意,當設定 $loginUrl 時,調用此方法將不會終止應用程式執行。

public yii\web\Response loginRequired ( $checkAjax true, $checkAcceptHeader true )
$checkAjax boolean

是否檢查請求是否為 AJAX 請求。當此值為 true 且請求為 AJAX 請求時,目前的 URL (對於 AJAX 請求) 將不會設定為返回 URL。

$checkAcceptHeader boolean

是否檢查請求是否接受 HTML 回應。預設為 true。當此值為 true 且請求不接受 HTML 回應時,目前的 URL 將不會設定為返回 URL。此外,不會重新導向使用者,而是拋出 ForbiddenHttpException 異常。此參數自 2.0.8 版本起可用。

return yii\web\Response

如果設定了 $loginUrl,則為重新導向回應

throws yii\web\ForbiddenHttpException

如果未設定 $loginUrl 或重新導向不適用,則為 "拒絕存取" HTTP 異常。

                public function loginRequired($checkAjax = true, $checkAcceptHeader = true)
{
    $request = Yii::$app->getRequest();
    $canRedirect = !$checkAcceptHeader || $this->checkRedirectAcceptable();
    if (
        $this->enableSession
        && $request->getIsGet()
        && (!$checkAjax || !$request->getIsAjax())
        && $canRedirect
    ) {
        $this->setReturnUrl($request->getAbsoluteUrl());
    }
    if ($this->loginUrl !== null && $canRedirect) {
        $loginUrl = (array) $this->loginUrl;
        if ($loginUrl[0] !== Yii::$app->requestedRoute) {
            return Yii::$app->getResponse()->redirect($this->loginUrl);
        }
    }
    throw new ForbiddenHttpException(Yii::t('yii', 'Login Required'));
}

            
logout() public method

登出目前使用者。

這將移除與驗證相關的 session 資料。如果 $destroySession 為 true,則將移除所有 session 資料。

public boolean logout ( $destroySession true )
$destroySession boolean

是否銷毀整個 session。預設為 true。如果 $enableSession 為 false,則此參數將被忽略。

return boolean

使用者是否已登出

                public function logout($destroySession = true)
{
    $identity = $this->getIdentity();
    if ($identity !== null && $this->beforeLogout($identity)) {
        $this->switchIdentity(null);
        $id = $identity->getId();
        $ip = Yii::$app->getRequest()->getUserIP();
        Yii::info("User '$id' logged out from $ip.", __METHOD__);
        if ($destroySession && $this->enableSession) {
            Yii::$app->getSession()->destroy();
        }
        $this->afterLogout($identity);
    }
    return $this->getIsGuest();
}

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

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

            
regenerateCsrfToken() protected method (available since version 2.0.14.2)

重新產生 CSRF 權杖

protected void regenerateCsrfToken ( )

                protected function regenerateCsrfToken()
{
    $request = Yii::$app->getRequest();
    if ($request->enableCsrfCookie || $this->enableSession) {
        $request->getCsrfToken(true);
    }
}

            
removeIdentityCookie() protected method (available since version 2.0.9)

移除身分 cookie。

$enableAutoLogin 為 true 時,使用此方法。

protected void removeIdentityCookie ( )

                protected function removeIdentityCookie()
{
    Yii::$app->getResponse()->getCookies()->remove(Yii::createObject(array_merge($this->identityCookie, [
        'class' => 'yii\web\Cookie',
    ])));
}

            
renewAuthStatus() protected method

使用來自 session 和 cookie 的資訊更新驗證狀態。

此方法將嘗試使用 $idParam session 變數來確定使用者身分。

如果設定了 $authTimeout,此方法將刷新計時器。

如果無法通過 session 確定使用者身分,則如果 $enableAutoLogin 為 true,此方法將嘗試 通過 cookie 登入

protected void renewAuthStatus ( )

                protected function renewAuthStatus()
{
    $session = Yii::$app->getSession();
    $id = $session->getHasSessionId() || $session->getIsActive() ? $session->get($this->idParam) : null;
    if ($id === null) {
        $identity = null;
    } else {
        /* @var $class IdentityInterface */
        $class = $this->identityClass;
        $identity = $class::findIdentity($id);
        if ($identity === null) {
            $this->switchIdentity(null);
        }
    }
    if ($identity !== null) {
        $authKey = $session->get($this->authKeyParam);
        if ($authKey !== null && !$identity->validateAuthKey($authKey)) {
            $identity = null;
            $ip = Yii::$app->getRequest()->getUserIP();
            Yii::warning("Invalid session auth key attempted for user '$id' from $ip: $authKey", __METHOD__);
        }
    }
    $this->setIdentity($identity);
    if ($identity !== null && ($this->authTimeout !== null || $this->absoluteAuthTimeout !== null)) {
        $expire = $this->authTimeout !== null ? $session->get($this->authTimeoutParam) : null;
        $expireAbsolute = $this->absoluteAuthTimeout !== null ? $session->get($this->absoluteAuthTimeoutParam) : null;
        if ($expire !== null && $expire < time() || $expireAbsolute !== null && $expireAbsolute < time()) {
            $this->logout(false);
        } elseif ($this->authTimeout !== null) {
            $session->set($this->authTimeoutParam, time() + $this->authTimeout);
        }
    }
    if ($this->enableAutoLogin) {
        if ($this->getIsGuest()) {
            $this->loginByCookie();
        } elseif ($this->autoRenewCookie) {
            $this->renewIdentityCookie();
        }
    }
}

            
renewIdentityCookie() protected method

更新身分 cookie。

此方法將身分 cookie 的到期時間設定為目前時間加上原始指定的 cookie 持續時間。

protected void renewIdentityCookie ( )

                protected function renewIdentityCookie()
{
    $name = $this->identityCookie['name'];
    $value = Yii::$app->getRequest()->getCookies()->getValue($name);
    if ($value !== null) {
        $data = json_decode($value, true);
        if (is_array($data) && isset($data[2])) {
            $cookie = Yii::createObject(array_merge($this->identityCookie, [
                'class' => 'yii\web\Cookie',
                'value' => $value,
                'expire' => time() + (int) $data[2],
            ]));
            Yii::$app->getResponse()->getCookies()->add($cookie);
        }
    }
}

            
sendIdentityCookie() protected method

傳送身分 cookie。

$enableAutoLogin 為 true 時,使用此方法。它將 $idauth key 和基於 cookie 的登入資訊的持續時間保存在 cookie 中。

另請參閱 loginByCookie()

protected void sendIdentityCookie ( $identity, $duration )
$identity yii\web\IdentityInterface
變數 $duration integer

使用者可以保持登入狀態的秒數。

                protected function sendIdentityCookie($identity, $duration)
{
    $cookie = Yii::createObject(array_merge($this->identityCookie, [
        'class' => 'yii\web\Cookie',
        'value' => json_encode([
            $identity->getId(),
            $identity->getAuthKey(),
            $duration,
        ], JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE),
        'expire' => time() + $duration,
    ]));
    Yii::$app->getResponse()->getCookies()->add($cookie);
}

            
setIdentity() public method

設定使用者身分物件。

請注意,此方法不處理 session 或 cookie。您通常應該使用 switchIdentity() 來更改當前使用者的身分。

public void setIdentity ( $identity )
$identity yii\web\IdentityInterface|null

與目前登入使用者關聯的身分物件。如果為 null,則表示目前使用者將是以訪客身分,且沒有任何關聯的身分。

throws yii\base\InvalidValueException

如果 $identity 物件未實作 yii\web\IdentityInterface

                public function setIdentity($identity)
{
    if ($identity instanceof IdentityInterface) {
        $this->_identity = $identity;
    } elseif ($identity === null) {
        $this->_identity = null;
    } else {
        throw new InvalidValueException('The identity object must implement IdentityInterface.');
    }
    $this->_access = [];
}

            
setReturnUrl() public method

將 URL 記住在 session 中,以便稍後可透過 getReturnUrl() 擷取回來。

public void setReturnUrl ( $url )
$url string|array

使用者登入後應重新導向到的 URL。如果給定一個陣列,將調用 yii\web\UrlManager::createUrl() 以建立相應的 URL。陣列的第一個元素應為路由,其餘的名稱-值對是用於建構 URL 的 GET 參數。例如:

['admin/index', 'ref' => 1]

                public function setReturnUrl($url)
{
    Yii::$app->getSession()->set($this->returnUrlParam, $url);
}

            
switchIdentity() public method

為目前使用者切換到新的身分。

$enableSession 為 true 時,此方法可能會根據 $duration 的值使用 session 和/或 cookie 來儲存使用者身分資訊。有關更多詳細資訊,請參閱 login()

當需要將目前使用者與相應的身分資訊關聯時,主要由 login()logout()loginByCookie() 調用此方法。

public void switchIdentity ( $identity, $duration 0 )
$identity yii\web\IdentityInterface|null

要與目前使用者關聯的身分資訊。如果為 null,則表示將目前使用者切換為訪客。

變數 $duration integer

使用者可以保持登入狀態的秒數。僅當 $identity 不為 null 時才使用此參數。

                public function switchIdentity($identity, $duration = 0)
{
    $this->setIdentity($identity);
    if (!$this->enableSession) {
        return;
    }
    /* Ensure any existing identity cookies are removed. */
    if ($this->enableAutoLogin && ($this->autoRenewCookie || $identity === null)) {
        $this->removeIdentityCookie();
    }
    $session = Yii::$app->getSession();
    $session->regenerateID(true);
    $session->remove($this->idParam);
    $session->remove($this->authTimeoutParam);
    $session->remove($this->authKeyParam);
    if ($identity) {
        $session->set($this->idParam, $identity->getId());
        $session->set($this->authKeyParam, $identity->getAuthKey());
        if ($this->authTimeout !== null) {
            $session->set($this->authTimeoutParam, time() + $this->authTimeout);
        }
        if ($this->absoluteAuthTimeout !== null) {
            $session->set($this->absoluteAuthTimeoutParam, time() + $this->absoluteAuthTimeout);
        }
        if ($this->enableAutoLogin && $duration > 0) {
            $this->sendIdentityCookie($identity, $duration);
        }
    }
}

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