0 追蹤者

類別 yii\web\UrlManager

繼承關係yii\web\UrlManager » yii\base\Component » yii\base\BaseObject
實作介面yii\base\Configurable
自版本2.0
原始碼 https://github.com/yiisoft/yii2/blob/master/framework/web/UrlManager.php

UrlManager 處理 HTTP 請求解析和基於一組規則建立 URL。

UrlManager 預設在 yii\base\Application 中配置為應用程式元件。您可以透過 Yii::$app->urlManager 存取該實例。

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

'urlManager' => [
    'enablePrettyUrl' => true,
    'rules' => [
        // your rules go here
    ],
    // ...
]

規則是實作 yii\web\UrlRuleInterface 的類別,預設為 yii\web\UrlRule。對於巢狀規則,還有 yii\web\GroupUrlRule 類別。

有關 UrlManager 的更多詳細資訊和使用方式,請參閱路由指南文章

公共屬性

隱藏繼承的屬性

屬性 類型 描述 定義於
$baseUrl string createUrl() 使用的基本 URL,用於加在建立的 URL 前面。 yii\web\UrlManager
$behaviors yii\base\Behavior[] 附加到此元件的行為列表。 yii\base\Component
$cache yii\caching\CacheInterface|array|string|boolean 快取物件或快取物件的應用程式元件 ID。 yii\web\UrlManager
$cacheKey string 快取規則的快取鍵 yii\web\UrlManager
$enablePrettyUrl boolean 是否啟用美化 URL。 yii\web\UrlManager
$enableStrictParsing boolean 是否啟用嚴格解析。 yii\web\UrlManager
$hostInfo string 主機資訊 (例如 https://www.example.com),由 createAbsoluteUrl() 使用,用於加在建立的 URL 前面。 yii\web\UrlManager
$normalizer yii\web\UrlNormalizer|array|string|false 此 UrlManager 使用的 yii\web\UrlNormalizer 的配置。 yii\web\UrlManager
$routeParam string 路由的 GET 參數名稱。 yii\web\UrlManager
$ruleConfig array URL 規則的預設配置。 yii\web\UrlManager
$rules array $enablePrettyUrltrue 時,用於建立和解析 URL 的規則。 yii\web\UrlManager
$scriptUrl string 入口腳本 URL,由 createUrl() 使用,用於加在建立的 URL 前面。 yii\web\UrlManager
$showScriptName boolean 是否在建構的 URL 中顯示入口腳本名稱。 yii\web\UrlManager
$suffix string $enablePrettyUrltrue 時使用的 URL 後綴。 yii\web\UrlManager

受保護的屬性

隱藏繼承的屬性

屬性 類型 描述 定義於

公共方法

隱藏繼承的方法

方法 描述 定義於
__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
addRules() 新增額外的 URL 規則。 yii\web\UrlManager
attachBehavior() 將行為附加到此元件。 yii\base\Component
attachBehaviors() 將行為列表附加到元件。 yii\base\Component
behaviors() 傳回此元件應表現為的行為列表。 yii\base\Component
canGetProperty() 傳回一個值,指示屬性是否可讀取。 yii\base\Component
canSetProperty() 傳回一個值,指示屬性是否可設定。 yii\base\Component
className() 傳回此類別的完整限定名稱。 yii\base\BaseObject
createAbsoluteUrl() 使用給定的路由和查詢參數建立絕對 URL。 yii\web\UrlManager
createUrl() 使用給定的路由和查詢參數建立 URL。 yii\web\UrlManager
detachBehavior() 從元件分離行為。 yii\base\Component
detachBehaviors() 從元件分離所有行為。 yii\base\Component
ensureBehaviors() 確保在 behaviors() 中宣告的行為已附加到此組件。 yii\base\Component
getBaseUrl() 傳回由 createUrl() 使用以附加到建立的 URL 的基礎 URL。 yii\web\UrlManager
getBehavior() 傳回具名的行為物件。 yii\base\Component
getBehaviors() 傳回附加到此組件的所有行為。 yii\base\Component
getHostInfo() 傳回由 createAbsoluteUrl() 使用以附加到建立的 URL 的主機資訊。 yii\web\UrlManager
getScriptUrl() 傳回由 createUrl() 使用以附加到建立的 URL 的入口腳本 URL。 yii\web\UrlManager
hasEventHandlers() 傳回一個值,指示是否有任何處理常式附加到具名事件。 yii\base\Component
hasMethod() 傳回一個值,指示是否已定義方法。 yii\base\Component
hasProperty() 傳回一個值,指示是否為此組件定義了屬性。 yii\base\Component
init() 初始化 UrlManager。 yii\web\UrlManager
off() 從此組件分離現有的事件處理常式。 yii\base\Component
on() 將事件處理常式附加到事件。 yii\base\Component
parseRequest() 解析使用者請求。 yii\web\UrlManager
setBaseUrl() 設定由 createUrl() 使用以附加到建立的 URL 的基礎 URL。 yii\web\UrlManager
setHostInfo() 設定由 createAbsoluteUrl() 使用以附加到建立的 URL 的主機資訊。 yii\web\UrlManager
setScriptUrl() 設定由 createUrl() 使用以附加到建立的 URL 的入口腳本 URL。 yii\web\UrlManager
trigger() 觸發事件。 yii\base\Component

Protected Methods

隱藏繼承的方法

方法 描述 定義於
buildRules() 從給定的規則宣告建立 URL 規則物件。 yii\web\UrlManager
canBeCached() 傳回一個值,指示是否應在內部快取中快取規則的 createUrl() 結果。 yii\web\UrlManager
getBuiltRulesFromCache() 從快取提供與 $ruleDeclarations 關聯的已建立 URL 規則。 yii\web\UrlManager
getUrlFromCache() 如果存在,則從內部快取取得 URL。 yii\web\UrlManager
setBuiltRulesCache() 使用 $rulesDeclaration 作為快取金鑰的一部分,將 $builtRules 儲存到快取。 yii\web\UrlManager
setRuleToCache() 將規則 (例如 yii\web\UrlRule) 儲存到內部快取。 yii\web\UrlManager

Property Details

隱藏繼承的屬性

$baseUrl public property

createUrl() 使用的基本 URL,用於加在建立的 URL 前面。

public string $baseUrl null
$cache public property

快取物件或快取物件的應用程式組件 ID。這也可以是一個陣列,用於在您不想使用應用程式組件時建立 yii\caching\CacheInterface 實例。編譯的 URL 規則將透過此快取物件進行快取(如果可用)。

在建立 UrlManager 物件之後,如果您想變更此屬性,則應僅將其指定為快取物件。如果您不想快取 URL 規則,請將此屬性設定為 falsenull

快取項目會儲存在快取配置中由 $defaultDuration 設定的時間內,預設情況下為無限期。如果您的 $rules 經常變更,您可能需要調整此值。

$cacheKey protected property (自版本 2.0.8 起可用)

快取規則的快取鍵

protected string $cacheKey __CLASS__
$enablePrettyUrl public property

是否啟用美化 URL。美化 URL 不是將所有參數放在 URL 的查詢字串部分中,而是允許使用路徑資訊來表示某些參數,因此可以產生更使用者友好的 URL,例如 "/news/Yii-is-released" 而不是 "/index.php?r=news%2Fview&id=100"。

public boolean $enablePrettyUrl false
$enableStrictParsing public property

是否啟用嚴格解析。如果啟用嚴格解析,則傳入的請求 URL 必須至少符合 $rules 中的其中一項規則,才能被視為有效的請求。否則,請求的路徑資訊部分將被視為請求的路徑。此屬性僅在 $enablePrettyUrltrue 時使用。

$hostInfo public property

主機資訊 (例如 https://www.example.com),由 createAbsoluteUrl() 使用,用於加在建立的 URL 前面。

public string $hostInfo null
$normalizer public property (自版本 2.0.10 起可用)

此 UrlManager 使用的 yii\web\UrlNormalizer 的組態。預設值為 false,表示將跳過正規化。如果您希望啟用 URL 正規化,則應手動配置此屬性。例如

[
    'class' => 'yii\web\UrlNormalizer',
    'collapseSlashes' => true,
    'normalizeTrailingSlash' => true,
]
$routeParam public property

路由的 GET 參數名稱。僅當 $enablePrettyUrlfalse 時才使用此屬性。

public string $routeParam 'r'
$ruleConfig public property

URL 規則的預設配置。透過 $rules 指定的個別規則配置,在配置規則的相同屬性時將優先。

public array $ruleConfig = [
    
'class' => 'yii\web\UrlRule',
]
$rules public property

$enablePrettyUrltrue 時,用於建立和解析 URL 的規則。$enablePrettyUrltrue 時,才使用此屬性。陣列中的每個元素都是用於建立單個 URL 規則的配置陣列。配置將首先與 $ruleConfig 合併,然後再用於建立規則物件。

如果規則僅指定 patternroute,則可以使用特殊的快捷方式格式:'pattern' => 'route'。也就是說,可以使用索引鍵來表示模式,並使用值來表示對應的路徑,而不是使用配置陣列。例如,'post/<id:\d+>' => 'post/view'

對於 RESTful 路由,上述快捷方式格式也允許您指定規則應套用的 HTTP 動詞。您可以透過將其放在模式前面並用空格分隔來做到這一點。例如,'PUT post/<id:\d+>' => 'post/update'。您可以透過用逗號分隔多個動詞,例如:'POST,PUT post/index' => 'post/create'。快捷方式格式中支援的動詞為:GET、HEAD、POST、PUT、PATCH 和 DELETE。請注意,當以此方式指定動詞時,mode 將設定為 PARSING_ONLY,因此您通常不會為正常的 GET 請求指定動詞。

以下是 RESTful CRUD 控制器的組態範例

[
    'dashboard' => 'site/index',

    'POST <controller:[\w-]+>' => '<controller>/create',
    '<controller:[\w-]+>s' => '<controller>/index',

    'PUT <controller:[\w-]+>/<id:\d+>'    => '<controller>/update',
    'DELETE <controller:[\w-]+>/<id:\d+>' => '<controller>/delete',
    '<controller:[\w-]+>/<id:\d+>'        => '<controller>/view',
];

請注意,如果您在建立 UrlManager 物件後修改此屬性,請確保使用規則物件而不是規則組態來填入陣列。

public array $rules = []
$scriptUrl public property

入口腳本 URL,由 createUrl() 使用,用於加在建立的 URL 前面。

public string $scriptUrl null
$showScriptName public property

是否在建構的 URL 中顯示入口腳本名稱。預設值為 true。僅當 $enablePrettyUrltrue 時才使用此屬性。

public boolean $showScriptName true
$suffix public property

$enablePrettyUrltrue 時使用的 URL 後綴。例如,可以使用 ".html",以便 URL 看起來像指向靜態 HTML 頁面。僅當 $enablePrettyUrltrue 時才使用此屬性。

public string $suffix null

Method Details

隱藏繼承的方法

__call() public method

Defined in: yii\base\Component::__call()

呼叫指定的非類別方法。

此方法將檢查是否有任何附加的行為具有具名方法,如果有的話,將執行該方法。

請勿直接呼叫此方法,因為它是 PHP 魔術方法,當呼叫未知方法時,將會隱式呼叫此方法。

public mixed __call ( $name, $params )
$name string

方法名稱

$params array

方法參數

return mixed

方法傳回值

throws yii\base\UnknownMethodException

當呼叫未知方法時

                public function __call($name, $params)
{
    $this->ensureBehaviors();
    foreach ($this->_behaviors as $object) {
        if ($object->hasMethod($name)) {
            return call_user_func_array([$object, $name], $params);
        }
    }
    throw new UnknownMethodException('Calling unknown method: ' . get_class($this) . "::$name()");
}

            
__clone() public method

Defined in: yii\base\Component::__clone()

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

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

public void __clone ( )

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

            
__construct() public method

Defined in: yii\base\BaseObject::__construct()

建構子。

預設實作會執行兩件事

  • 使用給定的組態 $config 初始化物件。
  • 呼叫 init()

如果此方法在子類別中被覆寫,則建議

  • 建構子的最後一個參數是組態陣列,如這裡的 $config
  • 在建構子的結尾呼叫父實作。
public void __construct ( $config = [] )
$config array

將用於初始化物件屬性的名稱-值對

                public function __construct($config = [])
{
    if (!empty($config)) {
        Yii::configure($this, $config);
    }
    $this->init();
}

            
__get() public method

Defined in: yii\base\Component::__get()

傳回元件屬性的值。

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

  • getter 定義的屬性:傳回 getter 結果
  • 行為的屬性:傳回行為屬性值

請勿直接呼叫此方法,因為它是 PHP 魔術方法,當執行 $value = $component->property; 時,將會隱式呼叫此方法。

另請參閱 __set()

public mixed __get ( $name )
$name string

屬性名稱

return mixed

屬性值或行為的屬性值

throws yii\base\UnknownPropertyException

如果未定義屬性

throws yii\base\InvalidCallException

如果屬性為唯寫。

                public function __get($name)
{
    $getter = 'get' . $name;
    if (method_exists($this, $getter)) {
        // read property, e.g. getName()
        return $this->$getter();
    }
    // behavior property
    $this->ensureBehaviors();
    foreach ($this->_behaviors as $behavior) {
        if ($behavior->canGetProperty($name)) {
            return $behavior->$name;
        }
    }
    if (method_exists($this, 'set' . $name)) {
        throw new InvalidCallException('Getting write-only property: ' . get_class($this) . '::' . $name);
    }
    throw new UnknownPropertyException('Getting unknown property: ' . get_class($this) . '::' . $name);
}

            
__isset() public method

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

Defined in: yii\base\Component::__set()

設定元件屬性的值。

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

  • setter 定義的屬性:設定屬性值
  • 格式為 "on xyz" 的事件:將處理常式附加到事件 "xyz"
  • 格式為 "as xyz" 的行為:附加名為 "xyz" 的行為
  • 行為的屬性:設定行為屬性值

請勿直接呼叫此方法,因為它是 PHP 魔術方法,當執行 $component->property = $value; 時,將會隱式呼叫此方法。

另請參閱 __get()

public void __set ( $name, $value )
$name string

屬性名稱或事件名稱

$value mixed

屬性值

throws yii\base\UnknownPropertyException

如果未定義屬性

throws yii\base\InvalidCallException

如果屬性為唯讀。

                public function __set($name, $value)
{
    $setter = 'set' . $name;
    if (method_exists($this, $setter)) {
        // set property
        $this->$setter($value);
        return;
    } elseif (strncmp($name, 'on ', 3) === 0) {
        // on event: attach event handler
        $this->on(trim(substr($name, 3)), $value);
        return;
    } elseif (strncmp($name, 'as ', 3) === 0) {
        // as behavior: attach behavior
        $name = trim(substr($name, 3));
        $this->attachBehavior($name, $value instanceof Behavior ? $value : Yii::createObject($value));
        return;
    }
    // behavior property
    $this->ensureBehaviors();
    foreach ($this->_behaviors as $behavior) {
        if ($behavior->canSetProperty($name)) {
            $behavior->$name = $value;
            return;
        }
    }
    if (method_exists($this, 'get' . $name)) {
        throw new InvalidCallException('Setting read-only property: ' . get_class($this) . '::' . $name);
    }
    throw new UnknownPropertyException('Setting unknown property: ' . get_class($this) . '::' . $name);
}

            
__unset() public method

Defined in: 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);
}

            
addRules() public method

新增額外的 URL 規則。

此方法將呼叫 buildRules() 以解析給定的規則宣告,然後將它們附加或插入到現有的 $rules

請注意,如果 $enablePrettyUrlfalse,則此方法將不執行任何操作。

public void addRules ( $rules, $append true )
$rules array

要新增的新規則。每個陣列元素代表單個規則宣告。請參閱 $rules 以取得可接受的規則格式。

$append boolean

是否透過將新規則附加到現有規則的末尾來新增它們。

                public function addRules($rules, $append = true)
{
    if (!$this->enablePrettyUrl) {
        return;
    }
    $rules = $this->buildRules($rules);
    if ($append) {
        $this->rules = array_merge($this->rules, $rules);
    } else {
        $this->rules = array_merge($rules, $this->rules);
    }
}

            
attachBehavior() public method

Defined in: yii\base\Component::attachBehavior()

將行為附加到此元件。

此方法將根據給定的組態建立行為物件。之後,將透過呼叫 yii\base\Behavior::attach() 方法,將行為物件附加到此組件。

另請參閱 detachBehavior()

public yii\base\Behavior attachBehavior ( $name, $behavior )
$name string

行為的名稱。

$behavior string|array|yii\base\Behavior

行為組態。這可以是下列其中一項

return yii\base\Behavior

行為物件

                public function attachBehavior($name, $behavior)
{
    $this->ensureBehaviors();
    return $this->attachBehaviorInternal($name, $behavior);
}

            
attachBehaviors() public method

Defined in: yii\base\Component::attachBehaviors()

將行為列表附加到元件。

每個行為都依其名稱編制索引,並且應該是 yii\base\Behavior 物件、指定行為類別的字串,或是用於建立行為的組態陣列。

另請參閱 attachBehavior()

public void attachBehaviors ( $behaviors )
$behaviors array

要附加到組件的行為清單

                public function attachBehaviors($behaviors)
{
    $this->ensureBehaviors();
    foreach ($behaviors as $name => $behavior) {
        $this->attachBehaviorInternal($name, $behavior);
    }
}

            
behaviors() public method

Defined in: yii\base\Component::behaviors()

傳回此元件應表現為的行為列表。

子類別可以覆寫此方法,以指定它們想要表現為的行為。

此方法的傳回值應為行為物件或組態的陣列,並依行為名稱編制索引。行為組態可以是指定行為類別的字串,也可以是以下結構的陣列

'behaviorName' => [
    'class' => 'BehaviorClass',
    'property1' => 'value1',
    'property2' => 'value2',
]

請注意,行為類別必須從 yii\base\Behavior 擴展。可以使用名稱或匿名方式附加行為。當名稱用作陣列索引鍵時,使用此名稱,稍後可以使用 getBehavior() 檢索行為,或使用 detachBehavior() 分離行為。匿名行為無法檢索或分離。

在此方法中宣告的行為將自動(按需)附加到組件。

public array behaviors ( )
return array

行為組態。

                public function behaviors()
{
    return [];
}

            
buildRules() protected method

從給定的規則宣告建立 URL 規則物件。

protected yii\web\UrlRuleInterface[] buildRules ( $ruleDeclarations )
$ruleDeclarations array

規則宣告。每個陣列元素代表單一規則宣告。可參考 $rules 以了解可接受的規則格式。

return yii\web\UrlRuleInterface[]

從給定的規則宣告建立的規則物件

throws yii\base\InvalidConfigException

若規則宣告無效

                protected function buildRules($ruleDeclarations)
{
    $builtRules = $this->getBuiltRulesFromCache($ruleDeclarations);
    if ($builtRules !== false) {
        return $builtRules;
    }
    $builtRules = [];
    $verbs = 'GET|HEAD|POST|PUT|PATCH|DELETE|OPTIONS';
    foreach ($ruleDeclarations as $key => $rule) {
        if (is_string($rule)) {
            $rule = ['route' => $rule];
            if (preg_match("/^((?:($verbs),)*($verbs))\\s+(.*)$/", $key, $matches)) {
                $rule['verb'] = explode(',', $matches[1]);
                $key = $matches[4];
            }
            $rule['pattern'] = $key;
        }
        if (is_array($rule)) {
            $rule = Yii::createObject(array_merge($this->ruleConfig, $rule));
        }
        if (!$rule instanceof UrlRuleInterface) {
            throw new InvalidConfigException('URL rule class must implement UrlRuleInterface.');
        }
        $builtRules[] = $rule;
    }
    $this->setBuiltRulesCache($ruleDeclarations, $builtRules);
    return $builtRules;
}

            
canBeCached() 受保護方法 (自版本 2.0.12 起可用)

傳回一個值,指示是否應在內部快取中快取規則的 createUrl() 結果。

另請參閱

protected boolean canBeCached ( yii\web\UrlRuleInterface $rule )
$rule yii\web\UrlRuleInterface
return boolean

如果結果應該被快取,則為 true,否則為 false

                protected function canBeCached(UrlRuleInterface $rule)
{
    return
        // if rule does not provide info about create status, we cache it every time to prevent bugs like #13350
        // @see https://github.com/yiisoft/yii2/pull/13350#discussion_r114873476
        !method_exists($rule, 'getCreateUrlStatus') || ($status = $rule->getCreateUrlStatus()) === null
        || $status === UrlRule::CREATE_STATUS_SUCCESS
        || $status & UrlRule::CREATE_STATUS_PARAMS_MISMATCH;
}

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

            
createAbsoluteUrl() 公開方法

使用給定的路由和查詢參數建立絕對 URL。

此方法會在 createUrl() 建立的 URL 前面加上 $hostInfo

請注意,與 yii\helpers\Url::toRoute() 不同,此方法始終將給定的路由視為絕對路由。

另請參閱 createUrl()

public string createAbsoluteUrl ( $params, $scheme null )
$params string|array

使用字串來表示路由(例如 site/index),或使用陣列來表示帶有查詢參數的路由(例如 ['site/index', 'param1' => 'value1'])。

$scheme string|null

用於 URL 的協定(httphttps 或空字串表示與協定相關的 URL)。如果未指定,將使用當前請求的協定。

return string

建立的 URL

                public function createAbsoluteUrl($params, $scheme = null)
{
    $params = (array) $params;
    $url = $this->createUrl($params);
    if (strpos($url, '://') === false) {
        $hostInfo = $this->getHostInfo();
        if (strncmp($url, '//', 2) === 0) {
            $url = substr($hostInfo, 0, strpos($hostInfo, '://')) . ':' . $url;
        } else {
            $url = $hostInfo . $url;
        }
    }
    return Url::ensureScheme($url, $scheme);
}

            
createUrl() 公開方法

使用給定的路由和查詢參數建立 URL。

您可以將路由指定為字串,例如 site/index。如果您想為正在建立的 URL 指定其他查詢參數,也可以使用陣列。陣列格式必須是

// generates: /index.php?r=site%2Findex&param1=value1&param2=value2
['site/index', 'param1' => 'value1', 'param2' => 'value2']

如果您想建立帶有錨點的 URL,可以使用帶有 # 參數的陣列格式。例如:

// generates: /index.php?r=site%2Findex&param1=value1#name
['site/index', 'param1' => 'value1', '#' => 'name']

建立的 URL 是相對 URL。使用 createAbsoluteUrl() 建立絕對 URL。

請注意,與 yii\helpers\Url::toRoute() 不同,此方法始終將給定的路由視為絕對路由。

public string createUrl ( $params )
$params string|array

使用字串來表示路由(例如 site/index),或使用陣列來表示帶有查詢參數的路由(例如 ['site/index', 'param1' => 'value1'])。

return string

建立的 URL

                public function createUrl($params)
{
    $params = (array) $params;
    $anchor = isset($params['#']) ? '#' . $params['#'] : '';
    unset($params['#'], $params[$this->routeParam]);
    $route = trim(isset($params[0]) ? $params[0] : '', '/');
    unset($params[0]);
    $baseUrl = $this->showScriptName || !$this->enablePrettyUrl ? $this->getScriptUrl() : $this->getBaseUrl();
    if ($this->enablePrettyUrl) {
        $cacheKey = $route . '?';
        foreach ($params as $key => $value) {
            if ($value !== null) {
                $cacheKey .= $key . '&';
            }
        }
        $url = $this->getUrlFromCache($cacheKey, $route, $params);
        if ($url === false) {
            /* @var $rule UrlRule */
            foreach ($this->rules as $rule) {
                if (in_array($rule, $this->_ruleCache[$cacheKey], true)) {
                    // avoid redundant calls of `UrlRule::createUrl()` for rules checked in `getUrlFromCache()`
                    // @see https://github.com/yiisoft/yii2/issues/14094
                    continue;
                }
                $url = $rule->createUrl($this, $route, $params);
                if ($this->canBeCached($rule)) {
                    $this->setRuleToCache($cacheKey, $rule);
                }
                if ($url !== false) {
                    break;
                }
            }
        }
        if ($url !== false) {
            if (strpos($url, '://') !== false) {
                if ($baseUrl !== '' && ($pos = strpos($url, '/', 8)) !== false) {
                    return substr($url, 0, $pos) . $baseUrl . substr($url, $pos) . $anchor;
                }
                return $url . $baseUrl . $anchor;
            } elseif (strncmp($url, '//', 2) === 0) {
                if ($baseUrl !== '' && ($pos = strpos($url, '/', 2)) !== false) {
                    return substr($url, 0, $pos) . $baseUrl . substr($url, $pos) . $anchor;
                }
                return $url . $baseUrl . $anchor;
            }
            $url = ltrim($url, '/');
            return "$baseUrl/{$url}{$anchor}";
        }
        if ($this->suffix !== null) {
            $route .= $this->suffix;
        }
        if (!empty($params) && ($query = http_build_query($params)) !== '') {
            $route .= '?' . $query;
        }
        $route = ltrim($route, '/');
        return "$baseUrl/{$route}{$anchor}";
    }
    $url = "$baseUrl?{$this->routeParam}=" . urlencode($route);
    if (!empty($params) && ($query = http_build_query($params)) !== '') {
        $url .= '&' . $query;
    }
    return $url . $anchor;
}

            
detachBehavior() 公開方法

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

從元件分離行為。

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

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

行為的名稱。

return yii\base\Behavior|null

分離的行為。如果行為不存在,則為 Null。

                public function detachBehavior($name)
{
    $this->ensureBehaviors();
    if (isset($this->_behaviors[$name])) {
        $behavior = $this->_behaviors[$name];
        unset($this->_behaviors[$name]);
        $behavior->detach();
        return $behavior;
    }
    return null;
}

            
detachBehaviors() 公開方法

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

從元件分離所有行為。

public void detachBehaviors ( )

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

            
ensureBehaviors() 公開方法

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

確保在 behaviors() 中宣告的行為已附加到此組件。

public void ensureBehaviors ( )

                public function ensureBehaviors()
{
    if ($this->_behaviors === null) {
        $this->_behaviors = [];
        foreach ($this->behaviors() as $name => $behavior) {
            $this->attachBehaviorInternal($name, $behavior);
        }
    }
}

            
getBaseUrl() 公開方法

傳回由 createUrl() 使用以附加到建立的 URL 的基礎 URL。

它預設為 yii\web\Request::$baseUrl。這主要用於當 $enablePrettyUrltrue$showScriptNamefalse 時。

public string getBaseUrl ( )
return string

createUrl() 使用的基本 URL,用於加在建立的 URL 前面。

throws yii\base\InvalidConfigException

如果在主控台應用程式中執行且未配置 $baseUrl

                public function getBaseUrl()
{
    if ($this->_baseUrl === null) {
        $request = Yii::$app->getRequest();
        if ($request instanceof Request) {
            $this->_baseUrl = $request->getBaseUrl();
        } else {
            throw new InvalidConfigException('Please configure UrlManager::baseUrl correctly as you are running a console application.');
        }
    }
    return $this->_baseUrl;
}

            
getBehavior() 公開方法

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

傳回具名的行為物件。

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

行為名稱

return yii\base\Behavior|null

行為物件,如果行為不存在,則為 null

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

            
getBehaviors() 公開方法

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

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

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

附加到此元件的行為列表

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

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

從快取提供與 $ruleDeclarations 關聯的已建立 URL 規則。

protected yii\web\UrlRuleInterface[]|false getBuiltRulesFromCache ( $ruleDeclarations )
$ruleDeclarations array

規則宣告。每個陣列元素代表單一規則宣告。可參考 $rules 以了解可接受的規則格式。

return yii\web\UrlRuleInterface[]|false

從給定的規則宣告建立的規則物件,或布林值 false,當此定義不存在快取項目時。

                protected function getBuiltRulesFromCache($ruleDeclarations)
{
    $cache = $this->ensureCache();
    if (!$cache) {
        return false;
    }
    return $cache->get([$this->cacheKey, $this->ruleConfig, $ruleDeclarations]);
}

            
getHostInfo() 公開方法

傳回由 createAbsoluteUrl() 使用以附加到建立的 URL 的主機資訊。

public string getHostInfo ( )
return string

主機資訊 (例如 https://www.example.com),由 createAbsoluteUrl() 使用,用於加在建立的 URL 前面。

throws yii\base\InvalidConfigException

如果在主控台應用程式中執行且未配置 $hostInfo

                public function getHostInfo()
{
    if ($this->_hostInfo === null) {
        $request = Yii::$app->getRequest();
        if ($request instanceof \yii\web\Request) {
            $this->_hostInfo = $request->getHostInfo();
        } else {
            throw new InvalidConfigException('Please configure UrlManager::hostInfo correctly as you are running a console application.');
        }
    }
    return $this->_hostInfo;
}

            
getScriptUrl() 公開方法

傳回由 createUrl() 使用以附加到建立的 URL 的入口腳本 URL。

它預設為 yii\web\Request::$scriptUrl。這主要用於當 $enablePrettyUrlfalse$showScriptNametrue 時。

public string getScriptUrl ( )
return string

入口腳本 URL,由 createUrl() 使用,用於加在建立的 URL 前面。

throws yii\base\InvalidConfigException

如果在主控台應用程式中執行且未配置 $scriptUrl

                public function getScriptUrl()
{
    if ($this->_scriptUrl === null) {
        $request = Yii::$app->getRequest();
        if ($request instanceof Request) {
            $this->_scriptUrl = $request->getScriptUrl();
        } else {
            throw new InvalidConfigException('Please configure UrlManager::scriptUrl correctly as you are running a console application.');
        }
    }
    return $this->_scriptUrl;
}

            
getUrlFromCache() 受保護方法 (自版本 2.0.8 起可用)

如果存在,則從內部快取取得 URL。

另請參閱 createUrl()

protected boolean|string getUrlFromCache ( $cacheKey, $route, $params )
$cacheKey string

產生的快取鍵以儲存資料。

$route string

路由(例如 site/index)。

$params array

規則參數。

return boolean|string

建立的 URL

                protected function getUrlFromCache($cacheKey, $route, $params)
{
    if (!empty($this->_ruleCache[$cacheKey])) {
        foreach ($this->_ruleCache[$cacheKey] as $rule) {
            /* @var $rule UrlRule */
            if (($url = $rule->createUrl($this, $route, $params)) !== false) {
                return $url;
            }
        }
    } else {
        $this->_ruleCache[$cacheKey] = [];
    }
    return false;
}

            
hasEventHandlers() 公開方法

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

傳回一個值,指示是否有任何處理常式附加到具名事件。

public boolean hasEventHandlers ( $name )
$name string

事件名稱

return boolean

是否有任何處理常式附加到事件。

                public function hasEventHandlers($name)
{
    $this->ensureBehaviors();
    if (!empty($this->_events[$name])) {
        return true;
    }
    foreach ($this->_eventWildcards as $wildcard => $handlers) {
        if (!empty($handlers) && StringHelper::matchWildcard($wildcard, $name)) {
            return true;
        }
    }
    return Event::hasHandlers($this, $name);
}

            
hasMethod() 公開方法

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

傳回一個值,指示是否已定義方法。

如果滿足以下條件,則定義了方法:

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

屬性名稱

$checkBehaviors boolean

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

return boolean

是否定義了方法

                public function hasMethod($name, $checkBehaviors = true)
{
    if (method_exists($this, $name)) {
        return true;
    } elseif ($checkBehaviors) {
        $this->ensureBehaviors();
        foreach ($this->_behaviors as $behavior) {
            if ($behavior->hasMethod($name)) {
                return true;
            }
        }
    }
    return false;
}

            
hasProperty() 公開方法

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

傳回一個值,指示是否為此組件定義了屬性。

如果滿足以下條件,則定義了屬性:

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

另請參閱

public boolean hasProperty ( $name, $checkVars true, $checkBehaviors true )
$name string

屬性名稱

$checkVars boolean

是否將成員變數視為屬性

$checkBehaviors boolean

是否將行為的屬性視為此元件的屬性

return boolean

是否定義了屬性

                public function hasProperty($name, $checkVars = true, $checkBehaviors = true)
{
    return $this->canGetProperty($name, $checkVars, $checkBehaviors) || $this->canSetProperty($name, false, $checkBehaviors);
}

            
init() 公開方法

初始化 UrlManager。

public void init ( )

                public function init()
{
    parent::init();
    if ($this->normalizer !== false) {
        $this->normalizer = Yii::createObject($this->normalizer);
        if (!$this->normalizer instanceof UrlNormalizer) {
            throw new InvalidConfigException('`' . get_class($this) . '::normalizer` should be an instance of `' . UrlNormalizer::className() . '` or its DI compatible configuration.');
        }
    }
    if (!$this->enablePrettyUrl) {
        return;
    }
    if (!empty($this->rules)) {
        $this->rules = $this->buildRules($this->rules);
    }
}

            
off() 公開方法

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

從此組件分離現有的事件處理常式。

此方法與 on() 相反。

注意:如果為事件名稱傳遞了萬用字元模式,則只會移除使用此萬用字元註冊的處理常式,而使用與此萬用字元匹配的純名稱註冊的處理常式將保留。

另請參閱 on()

public boolean off ( $name, $handler null )
$name string

事件名稱

$handler callable|null

要移除的事件處理常式。如果為 null,則會移除附加到命名事件的所有處理常式。

return boolean

如果找到並分離處理常式

                public function off($name, $handler = null)
{
    $this->ensureBehaviors();
    if (empty($this->_events[$name]) && empty($this->_eventWildcards[$name])) {
        return false;
    }
    if ($handler === null) {
        unset($this->_events[$name], $this->_eventWildcards[$name]);
        return true;
    }
    $removed = false;
    // plain event names
    if (isset($this->_events[$name])) {
        foreach ($this->_events[$name] as $i => $event) {
            if ($event[0] === $handler) {
                unset($this->_events[$name][$i]);
                $removed = true;
            }
        }
        if ($removed) {
            $this->_events[$name] = array_values($this->_events[$name]);
            return true;
        }
    }
    // wildcard event names
    if (isset($this->_eventWildcards[$name])) {
        foreach ($this->_eventWildcards[$name] as $i => $event) {
            if ($event[0] === $handler) {
                unset($this->_eventWildcards[$name][$i]);
                $removed = true;
            }
        }
        if ($removed) {
            $this->_eventWildcards[$name] = array_values($this->_eventWildcards[$name]);
            // remove empty wildcards to save future redundant regex checks:
            if (empty($this->_eventWildcards[$name])) {
                unset($this->_eventWildcards[$name]);
            }
        }
    }
    return $removed;
}

            
on() 公開方法

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

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

事件處理常式必須是有效的 PHP 回呼。以下是一些範例:

function ($event) { ... }         // anonymous function
[$object, 'handleClick']          // $object->handleClick()
['Page', 'handleClick']           // Page::handleClick()
'handleClick'                     // global function handleClick()

事件處理常式必須使用以下簽名定義:

function ($event)

其中 $event 是一個 yii\base\Event 物件,其中包含與事件相關聯的參數。

自 2.0.14 版本起,您可以將事件名稱指定為萬用字元模式

$component->on('event.group.*', function ($event) {
    Yii::trace($event->name . ' is triggered.');
});

另請參閱 off()

public void on ( $name, $handler, $data null, $append true )
$name string

事件名稱

$handler 可呼叫

事件處理常式

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

            
parseRequest() 公開方法

解析使用者請求。

public array|boolean parseRequest ( $request )
$request yii\web\Request

請求元件

return array|boolean

路由和相關聯的參數。如果 $enablePrettyUrlfalse,則後者始終為空。如果無法成功解析當前請求,則傳回 false

                public function parseRequest($request)
{
    if ($this->enablePrettyUrl) {
        /* @var $rule UrlRule */
        foreach ($this->rules as $rule) {
            $result = $rule->parseRequest($this, $request);
            if (YII_DEBUG) {
                Yii::debug([
                    'rule' => method_exists($rule, '__toString') ? $rule->__toString() : get_class($rule),
                    'match' => $result !== false,
                    'parent' => null,
                ], __METHOD__);
            }
            if ($result !== false) {
                return $result;
            }
        }
        if ($this->enableStrictParsing) {
            return false;
        }
        Yii::debug('No matching URL rules. Using default URL parsing logic.', __METHOD__);
        $suffix = (string) $this->suffix;
        $pathInfo = $request->getPathInfo();
        $normalized = false;
        if ($this->normalizer !== false) {
            $pathInfo = $this->normalizer->normalizePathInfo($pathInfo, $suffix, $normalized);
        }
        if ($suffix !== '' && $pathInfo !== '') {
            $n = strlen($this->suffix);
            if (substr_compare($pathInfo, $this->suffix, -$n, $n) === 0) {
                $pathInfo = substr($pathInfo, 0, -$n);
                if ($pathInfo === '') {
                    // suffix alone is not allowed
                    return false;
                }
            } else {
                // suffix doesn't match
                return false;
            }
        }
        if ($normalized) {
            // pathInfo was changed by normalizer - we need also normalize route
            return $this->normalizer->normalizeRoute([$pathInfo, []]);
        }
        return [$pathInfo, []];
    }
    Yii::debug('Pretty URL not enabled. Using default URL parsing logic.', __METHOD__);
    $route = $request->getQueryParam($this->routeParam, '');
    if (is_array($route)) {
        $route = '';
    }
    return [(string) $route, []];
}

            
setBaseUrl() 公開方法

設定由 createUrl() 使用以附加到建立的 URL 的基礎 URL。

這主要用於當 $enablePrettyUrltrue$showScriptNamefalse 時。

public void setBaseUrl ( $value )
$value string

createUrl() 使用的基本 URL,用於加在建立的 URL 前面。

                public function setBaseUrl($value)
{
    $this->_baseUrl = $value === null ? null : rtrim(Yii::getAlias($value), '/');
}

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

使用 $rulesDeclaration 作為快取金鑰的一部分,將 $builtRules 儲存到快取。

protected boolean setBuiltRulesCache ( $ruleDeclarations, $builtRules )
$ruleDeclarations array

規則宣告。每個陣列元素代表單一規則宣告。可參考 $rules 以了解可接受的規則格式。

$builtRules yii\web\UrlRuleInterface[]

從給定的規則宣告建立的規則物件。

return boolean

值是否成功儲存到快取中

                protected function setBuiltRulesCache($ruleDeclarations, $builtRules)
{
    $cache = $this->ensureCache();
    if (!$cache) {
        return false;
    }
    return $cache->set([$this->cacheKey, $this->ruleConfig, $ruleDeclarations], $builtRules);
}

            
setHostInfo() 公開方法

設定由 createAbsoluteUrl() 使用以附加到建立的 URL 的主機資訊。

public void setHostInfo ( $value )
$value string

主機資訊 (例如 "https://www.example.com"),createAbsoluteUrl() 會使用此資訊附加到建立的 URL 前面。

                public function setHostInfo($value)
{
    $this->_hostInfo = $value === null ? null : rtrim($value, '/');
}

            
setRuleToCache() 受保護方法 (自 2.0.8 版本起可用)

將規則 (例如 yii\web\UrlRule) 儲存到內部快取。

protected void setRuleToCache ( $cacheKey, yii\web\UrlRuleInterface $rule )
$cacheKey
$rule yii\web\UrlRuleInterface

                protected function setRuleToCache($cacheKey, UrlRuleInterface $rule)
{
    $this->_ruleCache[$cacheKey][] = $rule;
}

            
setScriptUrl() 公開方法

設定由 createUrl() 使用以附加到建立的 URL 的入口腳本 URL。

這主要用於 $enablePrettyUrlfalse$showScriptNametrue 的情況。

public void setScriptUrl ( $value )
$value string

入口腳本 URL,由 createUrl() 使用,用於加在建立的 URL 前面。

                public function setScriptUrl($value)
{
    $this->_scriptUrl = $value;
}

            
trigger() 公開方法

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

觸發事件。

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

public void trigger ( $name, yii\base\Event $event null )
$name string

事件名稱

$event yii\base\Event|null

事件實例。如果未設定,將會建立預設的 yii\base\Event 物件。

                public function trigger($name, Event $event = null)
{
    $this->ensureBehaviors();
    $eventHandlers = [];
    foreach ($this->_eventWildcards as $wildcard => $handlers) {
        if (StringHelper::matchWildcard($wildcard, $name)) {
            $eventHandlers[] = $handlers;
        }
    }
    if (!empty($this->_events[$name])) {
        $eventHandlers[] = $this->_events[$name];
    }
    if (!empty($eventHandlers)) {
        $eventHandlers = call_user_func_array('array_merge', $eventHandlers);
        if ($event === null) {
            $event = new Event();
        }
        if ($event->sender === null) {
            $event->sender = $this;
        }
        $event->handled = false;
        $event->name = $name;
        foreach ($eventHandlers as $handler) {
            $event->data = $handler[1];
            call_user_func($handler[0], $event);
            // stop further handling if the event is handled
            if ($event->handled) {
                return;
            }
        }
    }
    // invoke class-level attached handlers
    Event::trigger($this, $name, $event);
}