0 追蹤者

類別 yii\web\UrlRule

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

UrlRule 代表 yii\web\UrlManager 用於解析和產生 URL 的規則。

要定義您自己的 URL 解析和建立邏輯,您可以從此類別擴展,並將其新增至 yii\web\UrlManager::$rules,如下所示

'rules' => [
    ['class' => 'MyUrlRule', 'pattern' => '...', 'route' => 'site/index', ...],
    // ...
]

公開屬性

隱藏繼承的屬性

屬性 類型 描述 定義於
$createStatus integer|null 上次 createUrl() 呼叫後 URL 建立的狀態。 yii\web\UrlRule
$createUrlStatus integer|null 上次 createUrl() 呼叫後 URL 建立的狀態。 yii\web\UrlRule
$defaults array 此規則提供的預設 GET 參數(名稱 => 值)。 yii\web\UrlRule
$encodeParams boolean 指示是否應對參數進行 URL 編碼的值。 yii\web\UrlRule
$host string|null 用於解析和建立 URL 主機資訊部分(例如 https://example.com)的模式。 yii\web\UrlRule
$mode integer|null 指示此規則應同時用於請求解析和 URL 建立、僅解析或僅建立的值。 yii\web\UrlRule
$name string|null 此規則的名稱。 yii\web\UrlRule
$normalizer yii\web\UrlNormalizer|array|false|null 此規則使用的 yii\web\UrlNormalizer 的組態。 yii\web\UrlRule
$pattern string 用於解析和建立 URL 路徑資訊部分的模式。 yii\web\UrlRule
$placeholders array 用於匹配參數名稱的佔位符清單。 yii\web\UrlRule
$route string 控制器動作的路徑 yii\web\UrlRule
$suffix string|null 用於此規則的 URL 後綴。 yii\web\UrlRule
$verb string|array|null 此規則應匹配的 HTTP 動詞(例如 GET、POST、DELETE)。 yii\web\UrlRule

受保護的屬性

隱藏繼承的屬性

屬性 類型 描述 定義於

公開方法

隱藏繼承的方法

方法 描述 定義於
__call() 呼叫不是類別方法的具名方法。 yii\base\BaseObject
__construct() 建構子。 yii\base\BaseObject
__get() 傳回物件屬性的值。 yii\base\BaseObject
__isset() 檢查屬性是否已設定,即已定義且非 null。 yii\base\BaseObject
__set() 設定物件屬性的值。 yii\base\BaseObject
__toString() yii\web\UrlRule
__unset() 將物件屬性設為 null。 yii\base\BaseObject
canGetProperty() 傳回值,指示是否可以讀取屬性。 yii\base\BaseObject
canSetProperty() 傳回值,指示是否可以設定屬性。 yii\base\BaseObject
className() 傳回此類別的完整名稱。 yii\base\BaseObject
createUrl() 根據給定的路由和參數建立 URL。 yii\web\UrlRule
getCreateUrlStatus() 傳回上次 createUrl() 呼叫後 URL 建立的狀態。 yii\web\UrlRule
hasMethod() 傳回值,指示是否已定義方法。 yii\base\BaseObject
hasProperty() 傳回值,指示是否已定義屬性。 yii\base\BaseObject
init() 初始化此規則。 yii\web\UrlRule
parseRequest() 解析給定的請求並傳回對應的路由和參數。 yii\web\UrlRule

受保護的方法

隱藏繼承的方法

方法 描述 定義於
getNormalizer() yii\web\UrlRule
getParamRules() 傳回用於匹配參數的正規表示式清單。 yii\web\UrlRule
hasNormalizer() yii\web\UrlRule
substitutePlaceholderNames() 迭代 $placeholders 並檢查每個佔位符是否作為 $matches 陣列中的鍵存在。 yii\web\UrlRule

常數

隱藏繼承的常數

常數 描述 定義於
CREATE_STATUS_PARAMS_MISMATCH 4 表示上次 createUrl() 呼叫未成功產生 URL,因為參數不匹配或遺失。 yii\web\UrlRule
CREATE_STATUS_PARSING_ONLY 1 表示上次 createUrl() 呼叫未成功產生 URL,因為規則不支援建立 URL。 yii\web\UrlRule
CREATE_STATUS_ROUTE_MISMATCH 2 表示上次 createUrl() 呼叫未成功產生 URL,因為路由不匹配。 yii\web\UrlRule
CREATE_STATUS_SUCCESS 0 表示上次 createUrl() 呼叫成功產生 URL。 yii\web\UrlRule
CREATION_ONLY 2 $mode 設定為此值,以標記此規則僅用於 URL 建立。 yii\web\UrlRule
PARSING_ONLY 1 $mode 設定為此值,以標記此規則僅用於 URL 解析。 yii\web\UrlRule

屬性詳細資訊

隱藏繼承的屬性

$createStatus 受保護的屬性 (自版本 2.0.12 起可用)

上次 createUrl() 呼叫後 URL 建立的狀態。

protected integer|null $createStatus null
$createUrlStatus 公開屬性

上次 createUrl() 呼叫後 URL 建立的狀態。 如果規則未提供建立狀態的資訊,則為 null

$defaults 公開屬性

此規則提供的預設 GET 參數 (名稱 => 值)。 當此規則用於解析傳入的請求時,此屬性中宣告的值將被注入到 $_GET 中。

public array $defaults = []
$encodeParams 公開屬性

指示是否應對參數進行 URL 編碼的值。

public boolean $encodeParams true
$host 公開屬性

用於解析和建立 URL 主機資訊部分(例如 https://example.com)的模式。

另請參閱 $pattern

public string|null $host null
$mode 公開屬性

一個值,指示此規則是否應同時用於請求解析和 URL 建立、僅用於解析或僅用於建立。 如果未設定或為 0,則表示該規則同時用於請求解析和 URL 建立。 如果它是 PARSING_ONLY,則該規則僅用於請求解析。 如果它是 CREATION_ONLY,則該規則僅用於 URL 建立。

public integer|null $mode null
$name 公開屬性

此規則的名稱。 如果未設定,它將使用 $pattern 作為名稱。

public string|null $name null
$normalizer 公開屬性 (自版本 2.0.10 起可用)

此規則使用的 yii\web\UrlNormalizer 的組態。 如果為 null,將使用 yii\web\UrlManager::$normalizer,如果為 false,則此規則將跳過正規化。

$pattern 公開屬性

用於解析和建立 URL 路徑資訊部分的模式。

另請參閱

public string $pattern null
$placeholders 受保護的屬性 (自版本 2.0.7 起可用)

用於匹配參數名稱的佔位符清單。 用於 parseRequest()createUrl()。 在規則初始化時,$pattern 參數名稱將被替換為佔位符。 此陣列包含原始參數名稱及其佔位符之間的關係。 陣列鍵是佔位符,值是原始名稱。

另請參閱

protected array $placeholders = []
$route 公開屬性

控制器動作的路徑

public string $route null
$suffix 公開屬性

用於此規則的 URL 後綴。 例如,可以使用 ".html",使 URL 看起來像是指向靜態 HTML 頁面。 如果未設定,將使用 yii\web\UrlManager::$suffix 的值。

public string|null $suffix null
$verb 公開屬性

此規則應匹配的 HTTP 動詞(例如 GET、POST、DELETE)。 使用陣列表示此規則可能匹配的多個動詞。 如果未設定此屬性,則規則可以匹配任何動詞。 請注意,此屬性僅在解析請求時使用。 它在 URL 建立時被忽略。

public string|array|null $verb null

方法詳細資訊

隱藏繼承的方法

__call() 公開方法

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

呼叫不是類別方法的具名方法。

不要直接呼叫此方法,因為它是 PHP 魔術方法,當呼叫未知方法時,它會被隱式呼叫。

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

方法名稱

$params array

方法參數

return mixed

方法傳回值

throws yii\base\UnknownMethodException

當呼叫未知方法時

                public function __call($name, $params)
{
    throw new UnknownMethodException('Calling unknown method: ' . get_class($this) . "::$name()");
}

            
__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\BaseObject::__get()

傳回物件屬性的值。

不要直接呼叫此方法,因為它是 PHP 魔術方法,當執行 $value = $object->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)) {
        return $this->$getter();
    } elseif (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\BaseObject::__isset()

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

不要直接呼叫此方法,因為它是 PHP 魔術方法,當執行 isset($object->property) 時,它會被隱式呼叫。

請注意,如果未定義屬性,將傳回 false。

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

public boolean __isset ( $name )
$name string

屬性名稱或事件名稱

return boolean

具名屬性是否已設定(非 null)。

                public function __isset($name)
{
    $getter = 'get' . $name;
    if (method_exists($this, $getter)) {
        return $this->$getter() !== null;
    }
    return false;
}

            
__set() 公開方法

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

設定物件屬性的值。

不要直接呼叫此方法,因為它是 PHP 魔術方法,當執行 $object->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)) {
        $this->$setter($value);
    } elseif (method_exists($this, 'get' . $name)) {
        throw new InvalidCallException('Setting read-only property: ' . get_class($this) . '::' . $name);
    } else {
        throw new UnknownPropertyException('Setting unknown property: ' . get_class($this) . '::' . $name);
    }
}

            
__toString() 公開方法 (自版本 2.0.11 起可用)

public string __toString ( )

                public function __toString()
{
    $str = '';
    if ($this->verb !== null) {
        $str .= implode(',', $this->verb) . ' ';
    }
    if ($this->host !== null && strrpos($this->name, $this->host) === false) {
        $str .= $this->host . '/';
    }
    $str .= $this->name;
    if ($str === '') {
        return '/';
    }
    return $str;
}

            
__unset() 公開方法

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

將物件屬性設為 null。

不要直接呼叫此方法,因為它是 PHP 魔術方法,當執行 unset($object->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);
    } elseif (method_exists($this, 'get' . $name)) {
        throw new InvalidCallException('Unsetting read-only property: ' . get_class($this) . '::' . $name);
    }
}

            
canGetProperty() 公開方法

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

傳回值,指示是否可以讀取屬性。

屬性可讀取,如果

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

另請參閱 canSetProperty()

public boolean canGetProperty ( $name, $checkVars true )
$name string

屬性名稱

$checkVars boolean

是否將成員變數視為屬性

return boolean

屬性是否可讀取

                public function canGetProperty($name, $checkVars = true)
{
    return method_exists($this, 'get' . $name) || $checkVars && property_exists($this, $name);
}

            
canSetProperty() 公開方法

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

傳回值,指示是否可以設定屬性。

屬性可寫入,如果

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

另請參閱 canGetProperty()

public boolean canSetProperty ( $name, $checkVars true )
$name string

屬性名稱

$checkVars boolean

是否將成員變數視為屬性

return boolean

屬性是否可寫入

                public function canSetProperty($name, $checkVars = true)
{
    return method_exists($this, 'set' . $name) || $checkVars && property_exists($this, $name);
}

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

            
createUrl() 公開方法

根據給定的路由和參數建立 URL。

public string|boolean createUrl ( $manager, $route, $params )
$manager yii\web\UrlManager

URL 管理器

$route string

$route

$params array

路由。 它不應在開頭或結尾有斜線。

return 參數

string|boolean

                public function createUrl($manager, $route, $params)
{
    if ($this->mode === self::PARSING_ONLY) {
        $this->createStatus = self::CREATE_STATUS_PARSING_ONLY;
        return false;
    }
    $tr = [];
    // match the route part first
    if ($route !== $this->route) {
        if ($this->_routeRule !== null && preg_match($this->_routeRule, $route, $matches)) {
            $matches = $this->substitutePlaceholderNames($matches);
            foreach ($this->_routeParams as $name => $token) {
                if (isset($this->defaults[$name]) && strcmp($this->defaults[$name], $matches[$name]) === 0) {
                    $tr[$token] = '';
                } else {
                    $tr[$token] = $matches[$name];
                }
            }
        } else {
            $this->createStatus = self::CREATE_STATUS_ROUTE_MISMATCH;
            return false;
        }
    }
    // match default params
    // if a default param is not in the route pattern, its value must also be matched
    foreach ($this->defaults as $name => $value) {
        if (isset($this->_routeParams[$name])) {
            continue;
        }
        if (!isset($params[$name])) {
            // allow omit empty optional params
            // @see https://github.com/yiisoft/yii2/issues/10970
            if (in_array($name, $this->placeholders) && strcmp($value, '') === 0) {
                $params[$name] = '';
            } else {
                $this->createStatus = self::CREATE_STATUS_PARAMS_MISMATCH;
                return false;
            }
        }
        if (strcmp($params[$name], $value) === 0) { // strcmp will do string conversion automatically
            unset($params[$name]);
            if (isset($this->_paramRules[$name])) {
                $tr["<$name>"] = '';
            }
        } elseif (!isset($this->_paramRules[$name])) {
            $this->createStatus = self::CREATE_STATUS_PARAMS_MISMATCH;
            return false;
        }
    }
    // match params in the pattern
    foreach ($this->_paramRules as $name => $rule) {
        if (isset($params[$name]) && !is_array($params[$name]) && ($rule === '' || preg_match($rule, $params[$name]))) {
            $tr["<$name>"] = $this->encodeParams ? urlencode($params[$name]) : $params[$name];
            unset($params[$name]);
        } elseif (!isset($this->defaults[$name]) || isset($params[$name])) {
            $this->createStatus = self::CREATE_STATUS_PARAMS_MISMATCH;
            return false;
        }
    }
    $url = $this->trimSlashes(strtr($this->_template, $tr));
    if ($this->host !== null) {
        $pos = strpos($url, '/', 8);
        if ($pos !== false) {
            $url = substr($url, 0, $pos) . preg_replace('#/+#', '/', substr($url, $pos));
        }
    } elseif (strpos($url, '//') !== false) {
        $url = preg_replace('#/+#', '/', trim($url, '/'));
    }
    if ($url !== '') {
        $url .= ($this->suffix === null ? $manager->suffix : $this->suffix);
    }
    if (!empty($params) && ($query = http_build_query($params)) !== '') {
        $url .= '?' . $query;
    }
    $this->createStatus = self::CREATE_STATUS_SUCCESS;
    return $url;
}

            
建立的 URL,如果此規則不能用於建立此 URL,則為 false

傳回上次 createUrl() 呼叫後 URL 建立的狀態。

getCreateUrlStatus() 公開方法 (自版本 2.0.12 起可用)

另請參閱 $createStatus
return integer|null

上次 createUrl() 呼叫後 URL 建立的狀態。 如果規則未提供建立狀態的資訊,則為 null

                public function getCreateUrlStatus()
{
    return $this->createStatus;
}

            

getNormalizer() 受保護的方法 (自版本 2.0.10 起可用)
$manager yii\web\UrlManager

URL 管理器

                protected function getNormalizer($manager)
{
    if ($this->normalizer === null) {
        return $manager->normalizer;
    }
    return $this->normalizer;
}

            
protected yii\web\UrlNormalizer|null getNormalizer ( $manager )

傳回用於匹配參數的正規表示式清單。

protected array getParamRules ( )
return array

參數鍵與正則表達式規則。

                protected function getParamRules()
{
    return $this->_paramRules;
}

            
hasMethod() public method

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

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

預設的實作是呼叫 php 函數 method_exists()。當您實作 php 魔術方法 __call() 時,您可以覆寫此方法。

public boolean hasMethod ( $name )
$name string

方法名稱

return boolean

方法是否已定義

                public function hasMethod($name)
{
    return method_exists($this, $name);
}

            
hasNormalizer() protected method (自版本 2.0.10 起可用)

protected boolean hasNormalizer ( $manager )
$manager yii\web\UrlManager

URL 管理器

                protected function hasNormalizer($manager)
{
    return $this->getNormalizer($manager) instanceof UrlNormalizer;
}

            
hasProperty() public method

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

傳回值,指示是否已定義屬性。

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

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

另請參閱

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

屬性名稱

$checkVars boolean

是否將成員變數視為屬性

return boolean

屬性是否已定義

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

            
init() public method

初始化此規則。

public void init ( )

                public function init()
{
    if ($this->pattern === null) {
        throw new InvalidConfigException('UrlRule::pattern must be set.');
    }
    if ($this->route === null) {
        throw new InvalidConfigException('UrlRule::route must be set.');
    }
    if (is_array($this->normalizer)) {
        $normalizerConfig = array_merge(['class' => UrlNormalizer::className()], $this->normalizer);
        $this->normalizer = Yii::createObject($normalizerConfig);
    }
    if ($this->normalizer !== null && $this->normalizer !== false && !$this->normalizer instanceof UrlNormalizer) {
        throw new InvalidConfigException('Invalid config for UrlRule::normalizer.');
    }
    if ($this->verb !== null) {
        if (is_array($this->verb)) {
            foreach ($this->verb as $i => $verb) {
                $this->verb[$i] = strtoupper($verb);
            }
        } else {
            $this->verb = [strtoupper($this->verb)];
        }
    }
    if ($this->name === null) {
        $this->name = $this->pattern;
    }
    $this->preparePattern();
}

            
parseRequest() public method

解析給定的請求並傳回對應的路由和參數。

public array|boolean parseRequest ( $manager, $request )
$manager yii\web\UrlManager

URL 管理器

$request yii\web\Request

請求組件

return array|boolean

解析結果。路由和參數以陣列形式返回。如果為 false,則表示此規則不能用於解析此路徑資訊。

                public function parseRequest($manager, $request)
{
    if ($this->mode === self::CREATION_ONLY) {
        return false;
    }
    if (!empty($this->verb) && !in_array($request->getMethod(), $this->verb, true)) {
        return false;
    }
    $suffix = (string) ($this->suffix === null ? $manager->suffix : $this->suffix);
    $pathInfo = $request->getPathInfo();
    $normalized = false;
    if ($this->hasNormalizer($manager)) {
        $pathInfo = $this->getNormalizer($manager)->normalizePathInfo($pathInfo, $suffix, $normalized);
    }
    if ($suffix !== '' && $pathInfo !== '') {
        $n = strlen($suffix);
        if (substr_compare($pathInfo, $suffix, -$n, $n) === 0) {
            $pathInfo = substr($pathInfo, 0, -$n);
            if ($pathInfo === '') {
                // suffix alone is not allowed
                return false;
            }
        } else {
            return false;
        }
    }
    if ($this->host !== null) {
        $pathInfo = strtolower($request->getHostInfo()) . ($pathInfo === '' ? '' : '/' . $pathInfo);
    }
    if (!preg_match($this->pattern, $pathInfo, $matches)) {
        return false;
    }
    $matches = $this->substitutePlaceholderNames($matches);
    foreach ($this->defaults as $name => $value) {
        if (!isset($matches[$name]) || $matches[$name] === '') {
            $matches[$name] = $value;
        }
    }
    $params = $this->defaults;
    $tr = [];
    foreach ($matches as $name => $value) {
        if (isset($this->_routeParams[$name])) {
            $tr[$this->_routeParams[$name]] = $value;
            unset($params[$name]);
        } elseif (isset($this->_paramRules[$name])) {
            $params[$name] = $value;
        }
    }
    if ($this->_routeRule !== null) {
        $route = strtr($this->route, $tr);
    } else {
        $route = $this->route;
    }
    Yii::debug("Request parsed with URL rule: {$this->name}", __METHOD__);
    if ($normalized) {
        // pathInfo was changed by normalizer - we need also normalize route
        return $this->getNormalizer($manager)->normalizeRoute([$route, $params]);
    }
    return [$route, $params];
}

            
substitutePlaceholderNames() protected method (自版本 2.0.7 起可用)

迭代 $placeholders 並檢查每個佔位符是否作為 $matches 陣列中的鍵存在。

當找到時 - 將此佔位符鍵替換為匹配參數的適當名稱。用於 parseRequest(), createUrl()

另請參閱 $placeholders

protected array substitutePlaceholderNames ( array $matches )
$matches array

preg_match() 呼叫的結果

return array

帶有替換佔位符鍵的輸入陣列

                protected function substitutePlaceholderNames(array $matches)
{
    foreach ($this->placeholders as $placeholder => $name) {
        if (isset($matches[$placeholder])) {
            $matches[$name] = $matches[$placeholder];
            unset($matches[$placeholder]);
        }
    }
    return $matches;
}