類別 yii\rest\UrlRule
UrlRule 的目的是簡化 RESTful API 支援的 URL 規則建立。
UrlRule 最簡單的用法是在應用程式設定中宣告如下規則:
[
'class' => 'yii\rest\UrlRule',
'controller' => 'user',
]
上述程式碼將建立一整套 URL 規則,以支援以下 RESTful API 端點
'PUT,PATCH users/<id>' => 'user/update'
:更新使用者'DELETE users/<id>' => 'user/delete'
:刪除使用者'GET,HEAD users/<id>' => 'user/view'
:傳回使用者的詳細資料/概觀/選項'POST users' => 'user/create'
:建立新使用者'GET,HEAD users' => 'user/index'
:傳回使用者列表/概觀/選項'users/<id>' => 'user/options'
:處理使用者所有未處理的動詞'users' => 'user/options'
:處理使用者集合所有未處理的動詞
您可以設定 $only 和/或 $except 以停用上述某些規則。您可以設定 $patterns 以完全重新定義您自己的規則列表。您可以設定 $controller 與多個控制器 ID,以為所有這些控制器產生規則。例如,以下程式碼將停用 delete
規則,並為 user
和 post
控制器產生規則
[
'class' => 'yii\rest\UrlRule',
'controller' => ['user', 'post'],
'except' => ['delete'],
]
屬性 $controller 為必要項目,應代表一個或多個控制器 ID。如果控制器位於模組中,則每個控制器 ID 都應以模組 ID 為前綴。模式中使用的控制器 ID 將會自動複數化(例如,user
變成 users
,如上述範例所示)。
關於 UrlRule 的更多詳細資訊和用法,請參閱關於 REST 路由的指南文章。
公開屬性
屬性 | 類型 | 描述 | 定義於 |
---|---|---|---|
$controller | string|array | 此複合規則中的規則正在處理的控制器 ID(例如 user 、post-comment )。 |
yii\rest\UrlRule |
$createStatus | integer|null | 上次 createUrl() 呼叫後 URL 建立的狀態。 | yii\web\CompositeUrlRule |
$createUrlStatus | integer|null | 上次 createUrl() 呼叫後 URL 建立的狀態。 | yii\web\CompositeUrlRule |
$except | array | 應排除的動作列表。 | yii\rest\UrlRule |
$extraPatterns | array | 除了在 $patterns 中列出的那些以外,用於支援額外動作的模式。 | yii\rest\UrlRule |
$only | array | 可接受的動作列表。 | yii\rest\UrlRule |
$patterns | array | 用於建立 URL 規則的可能模式和相應動作的列表。 | yii\rest\UrlRule |
$pluralize | boolean (布林值) | 是否自動將控制器 (controllers) 的 URL 名稱設為複數形式。 | yii\rest\UrlRule |
$prefix | string|null | 所有模式共用的通用前綴字串。 | yii\rest\UrlRule |
$ruleConfig | array | 用於建立此規則中包含的每個 URL 規則的預設配置。 | yii\rest\UrlRule |
$rules | yii\web\UrlRuleInterface[] | 此複合規則中包含的 URL 規則。 | yii\web\CompositeUrlRule |
$suffix | string (字串) | 將指派給 yii\web\UrlRule::$suffix 以用於每個產生的規則的後綴。 | yii\rest\UrlRule |
$tokens | array | 應為每個模式替換的 token (令牌) 列表。 | yii\rest\UrlRule |
Public Methods (公有方法)
Hide inherited methods (隱藏繼承的方法)
Method (方法) | 描述 | 定義於 |
---|---|---|
__call() | 呼叫未定義為類別方法的具名方法。 | yii\base\BaseObject |
__construct() | Constructor (建構子)。 | yii\base\BaseObject |
__get() | 傳回物件屬性的值。 | yii\base\BaseObject |
__isset() | 檢查屬性是否已設定,即已定義且非 null。 | yii\base\BaseObject |
__set() | 設定物件屬性的值。 | yii\base\BaseObject |
__unset() | 將物件屬性設為 null。 | yii\base\BaseObject |
canGetProperty() | 傳回一個值,指示屬性是否可讀取。 | yii\base\BaseObject |
canSetProperty() | 傳回一個值,指示屬性是否可設定。 | yii\base\BaseObject |
className() | 傳回此類別的完整限定名稱。 | yii\base\BaseObject |
createUrl() | 根據給定的路由和參數建立 URL。 | yii\rest\UrlRule |
getCreateUrlStatus() | 傳回上次 createUrl() 呼叫後 URL 建立的狀態。 | yii\web\CompositeUrlRule |
hasMethod() | 傳回一個值,指示是否已定義方法。 | yii\base\BaseObject |
hasProperty() | 傳回一個值,指示是否已定義屬性。 | yii\base\BaseObject |
init() | 初始化物件。 | yii\rest\UrlRule |
parseRequest() | 解析給定的請求,並傳回對應的路由和參數。 | yii\rest\UrlRule |
Protected Methods (受保護的方法)
Hide inherited methods (隱藏繼承的方法)
Method (方法) | 描述 | 定義於 |
---|---|---|
createRule() | 使用給定的模式和動作建立 URL 規則。 | yii\rest\UrlRule |
createRules() | 建立應包含在此複合規則內的 URL 規則。 | yii\rest\UrlRule |
iterateRules() | 迭代指定的規則,並為每個規則呼叫 createUrl()。 | yii\web\CompositeUrlRule |
Property Details (屬性詳情)
此複合規則中的規則正在處理的控制器 ID(例如 user
、post-comment
)。如果控制器位於模組中,則應以模組 ID 為前綴(例如 admin/user
)。
預設情況下,當控制器 ID 放入產生的規則的模式中時,將會自動設為複數形式。如果您想明確指定控制器 ID 應如何出現在模式中,您可以使用一個陣列,其中陣列鍵 (key) 作為模式中的控制器 ID,而陣列值 (value) 為實際的控制器 ID。例如,['u' => 'user']
。
您也可以將多個控制器 ID 作為陣列傳遞。在這種情況下,此複合規則將為每個指定的控制器產生適用的 URL 規則。例如,['user', 'post']
。
應排除的動作列表。在此陣列中找到的任何動作將不會建立其 URL 規則。
另請參閱 $patterns。
可接受的動作列表。 如果非空,則只有此陣列中的動作才會建立對應的 URL 規則。
另請參閱 $patterns。
用於建立 URL 規則的可能模式和相應動作的列表。 鍵 (keys) 是模式,值 (values) 是對應的動作。 模式的格式為 Verbs Pattern
,其中 Verbs
代表以逗號分隔的 HTTP 動詞列表(沒有空格)。 如果未指定 Verbs
,則表示允許所有動詞。 Pattern
是可選的。 它將以 $prefix/$controller/ 為前綴,並且其中的 token (令牌) 將由 $tokens 替換。
是否自動將控制器 (controllers) 的 URL 名稱設為複數形式。 如果為 true,則控制器 ID 將以複數形式出現在 URL 中。 例如,user
控制器在 URL 中將顯示為 users
。
另請參閱 $controller。
用於建立此規則中包含的每個 URL 規則的預設配置。
將指派給 yii\web\UrlRule::$suffix 以用於每個產生的規則的後綴。
Method Details (方法詳情)
Hide inherited methods (隱藏繼承的方法)
Defined in: yii\base\BaseObject::__call()
呼叫未定義為類別方法的具名方法。
請勿直接呼叫此方法,因為它是一個 PHP magic method (魔術方法),當呼叫未知的方法時,它會被隱式呼叫。
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()");
}
Defined in: yii\base\BaseObject::__construct()
Constructor (建構子)。
預設實作會執行兩件事
- 使用給定的配置
$config
初始化物件。 - 呼叫 init()。
如果子類別中覆寫了此方法,建議
- 建構子的最後一個參數是一個配置陣列,就像此處的
$config
一樣。 - 在建構子的末尾呼叫父類別的實作。
public void __construct ( $config = [] ) | ||
$config | array |
將用於初始化物件屬性的 名稱-值 組 (Name-value pairs) |
public function __construct($config = [])
{
if (!empty($config)) {
Yii::configure($this, $config);
}
$this->init();
}
Defined in: yii\base\BaseObject::__get()
傳回物件屬性的值。
請勿直接呼叫此方法,因為它是一個 PHP magic method (魔術方法),當執行 $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);
}
Defined in: yii\base\BaseObject::__isset()
檢查屬性是否已設定,即已定義且非 null。
請勿直接呼叫此方法,因為它是一個 PHP magic method (魔術方法),當執行 isset($object->property)
時,它會被隱式呼叫。
請注意,如果未定義屬性,將傳回 false。
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;
}
Defined in: yii\base\BaseObject::__set()
設定物件屬性的值。
請勿直接呼叫此方法,因為它是一個 PHP magic method (魔術方法),當執行 $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);
}
}
Defined in: yii\base\BaseObject::__unset()
將物件屬性設為 null。
請勿直接呼叫此方法,因為它是一個 PHP magic method (魔術方法),當執行 unset($object->property)
時,它會被隱式呼叫。
請注意,如果未定義屬性,此方法將不執行任何操作。 如果屬性為唯讀,它將擲出例外。
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);
}
}
Defined in: 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);
}
Defined in: 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);
}
::class
。
Defined in: yii\base\BaseObject::className()
傳回此類別的完整限定名稱。
public static string className ( ) | ||
return | string (字串) |
此類別的完整限定名稱。 |
---|
public static function className()
{
return get_called_class();
}
使用給定的模式和動作建立 URL 規則。
protected yii\web\UrlRuleInterface createRule ( $pattern, $prefix, $action ) | ||
$pattern | string (字串) | |
$prefix | string (字串) | |
$action | string (字串) |
protected function createRule($pattern, $prefix, $action)
{
$verbs = 'GET|HEAD|POST|PUT|PATCH|DELETE|OPTIONS';
if (preg_match("/^((?:($verbs),)*($verbs))(?:\\s+(.*))?$/", $pattern, $matches)) {
$verbs = explode(',', $matches[1]);
$pattern = isset($matches[4]) ? $matches[4] : '';
} else {
$verbs = [];
}
$config = $this->ruleConfig;
$config['verb'] = $verbs;
$config['pattern'] = rtrim($prefix . '/' . strtr($pattern, $this->tokens), '/');
$config['route'] = $action;
$config['suffix'] = $this->suffix;
return Yii::createObject($config);
}
建立應包含在此複合規則內的 URL 規則。
protected yii\web\UrlRuleInterface[] createRules ( ) | ||
return | yii\web\UrlRuleInterface[] |
URL 規則 |
---|
protected function createRules()
{
$only = array_flip($this->only);
$except = array_flip($this->except);
$patterns = $this->extraPatterns + $this->patterns;
$rules = [];
foreach ($this->controller as $urlName => $controller) {
$prefix = trim($this->prefix . '/' . $urlName, '/');
foreach ($patterns as $pattern => $action) {
if (!isset($except[$action]) && (empty($only) || isset($only[$action]))) {
$rules[$urlName][] = $this->createRule($pattern, $prefix, $controller . '/' . $action);
}
}
}
return $rules;
}
根據給定的路由和參數建立 URL。
public string|boolean createUrl ( $manager, $route, $params ) | ||
$manager | yii\web\UrlManager |
URL 管理器 |
$route | string (字串) |
路由。 開頭或結尾不應有斜線。 |
$params | array |
參數 |
return | string|boolean |
建立的 URL,如果此規則不能用於建立此 URL,則為 false。 |
---|
public function createUrl($manager, $route, $params)
{
$this->createStatus = WebUrlRule::CREATE_STATUS_SUCCESS;
foreach ($this->controller as $urlName => $controller) {
if (strpos($route, $controller) !== false) {
/* @var $rules UrlRuleInterface[] */
$rules = $this->rules[$urlName];
$url = $this->iterateRules($rules, $manager, $route, $params);
if ($url !== false) {
return $url;
}
} else {
$this->createStatus |= WebUrlRule::CREATE_STATUS_ROUTE_MISMATCH;
}
}
if ($this->createStatus === WebUrlRule::CREATE_STATUS_SUCCESS) {
// create status was not changed - there is no rules configured
$this->createStatus = WebUrlRule::CREATE_STATUS_PARSING_ONLY;
}
return false;
}
Defined in: yii\web\CompositeUrlRule::getCreateUrlStatus()
傳回上次 createUrl() 呼叫後 URL 建立的狀態。
對於多個規則,狀態將通過位元運算子 or
組合(例如 UrlRule::CREATE_STATUS_PARSING_ONLY | UrlRule::CREATE_STATUS_PARAMS_MISMATCH
)。
另請參閱
public integer|null getCreateUrlStatus ( ) | ||
return | integer|null |
上次 createUrl() 呼叫後 URL 建立的狀態。 如果規則未提供有關建立狀態的資訊,則為 |
---|
public function getCreateUrlStatus()
{
return $this->createStatus;
}
Defined in: yii\base\BaseObject::hasMethod()
傳回一個值,指示是否已定義方法。
預設實作是對 php 函數 method_exists()
的呼叫。 當您實作 php magic method (魔術方法) __call()
時,您可以覆寫此方法。
public boolean hasMethod ( $name ) | ||
$name | string (字串) |
方法名稱 |
return | boolean (布林值) |
方法是否已定義 |
---|
public function hasMethod($name)
{
return method_exists($this, $name);
}
Defined in: 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);
}
初始化物件。
在物件使用給定的配置初始化後,此方法會在建構子的結尾被調用。
public void init ( ) |
public function init()
{
if (empty($this->controller)) {
throw new InvalidConfigException('"controller" must be set.');
}
$controllers = [];
foreach ((array) $this->controller as $urlName => $controller) {
if (is_int($urlName)) {
$urlName = $this->pluralize ? Inflector::pluralize($controller) : $controller;
}
$controllers[$urlName] = $controller;
}
$this->controller = $controllers;
$this->prefix = trim((string)$this->prefix, '/');
parent::init();
}
Defined in: yii\web\CompositeUrlRule::iterateRules()
迭代指定的規則,並為每個規則呼叫 createUrl()。
另請參閱 createUrl()。
protected boolean|string iterateRules ( $rules, $manager, $route, $params ) | ||
$rules | yii\web\UrlRuleInterface[] |
要迭代的規則。 |
$manager | yii\web\UrlManager |
URL 管理器 |
$route | string (字串) |
路由。 開頭或結尾不應有斜線。 |
$params | array |
參數 |
return | boolean|string |
建立的 URL,如果沒有指定的規則可以用於建立此 URL,則為 |
---|
protected function iterateRules($rules, $manager, $route, $params)
{
/* @var $rule UrlRule */
foreach ($rules as $rule) {
$url = $rule->createUrl($manager, $route, $params);
if ($url !== false) {
$this->createStatus = UrlRule::CREATE_STATUS_SUCCESS;
return $url;
}
if (
$this->createStatus === null
|| !method_exists($rule, 'getCreateUrlStatus')
|| $rule->getCreateUrlStatus() === null
) {
$this->createStatus = null;
} else {
$this->createStatus |= $rule->getCreateUrlStatus();
}
}
return false;
}
解析給定的請求,並傳回對應的路由和參數。
public array|boolean parseRequest ( $manager, $request ) | ||
$manager | yii\web\UrlManager |
URL 管理器 |
$request | yii\web\Request |
請求元件 |
return | array|boolean |
解析結果。路由與參數會以陣列形式回傳。如果為 false,表示此規則無法用於解析此路徑資訊。 |
---|
public function parseRequest($manager, $request)
{
$pathInfo = $request->getPathInfo();
if (
$this->prefix !== ''
&& strpos($this->prefix, '<') === false
&& strpos($pathInfo . '/', $this->prefix . '/') !== 0
) {
return false;
}
foreach ($this->rules as $urlName => $rules) {
if (strpos($pathInfo, $urlName) !== false) {
foreach ($rules as $rule) {
/* @var $rule WebUrlRule */
$result = $rule->parseRequest($manager, $request);
if (YII_DEBUG) {
Yii::debug([
'rule' => method_exists($rule, '__toString') ? $rule->__toString() : get_class($rule),
'match' => $result !== false,
'parent' => self::className(),
], __METHOD__);
}
if ($result !== false) {
return $result;
}
}
}
}
return false;
}
這個類別預設會將您嘗試存取資源的 ID 比對為數字。如果您的唯一識別符號不只是數字,例如 UUID V4,您可以在您的設定中覆寫
$tokens
成員變數以指定{id}
符記應該比對的內容。它使用 regex 比對。'urlManager' => [ ... 'rules' => [ [ 'class' => 'yii\rest\UrlRule', 'controller' => ['controllername'], 'tokens' => ['{id}' => '<id:\\w+>'], ], ], ],
這個範例將
{id}
比對為任何字母數字字元[a-zA-Z0-9_]
一次或多次。註冊 或 登入 以發表評論。