類別 yii\rest\ActiveController
ActiveController 實作了一組通用的動作,以支援對 ActiveRecord 的 RESTful 存取。
ActiveRecord 的類別應透過 $modelClass 指定,該類別必須實作 yii\db\ActiveRecordInterface。預設情況下,支援以下動作:
index
:模型列表view
:傳回模型的詳細資訊create
:建立新模型update
:更新現有模型delete
:刪除現有模型options
:傳回允許的 HTTP 方法
您可以透過覆寫 actions() 並取消設定相應的動作來停用其中一些動作。
若要新增動作,您可以覆寫 actions() 並附加新的動作類別,或撰寫新的動作方法。請確保您也覆寫 verbs(),以正確宣告新動作允許的 HTTP 方法。
您通常應該覆寫 checkAccess(),以檢查目前使用者是否具有對指定模型執行指定動作的權限。
有關 ActiveController 的更多詳細資訊和使用說明,請參閱關於 REST 控制器的指南文章。
公開屬性
Public Methods
Protected Methods
Method | 描述 | 定義於 |
---|---|---|
bindInjectedParams() | 根據動作方法簽名中的類型和名稱填寫參數。 | yii\base\Controller |
serializeData() | 序列化指定的資料。 | yii\rest\Controller |
verbs() | 宣告允許的 HTTP 動詞。 | yii\rest\ActiveController |
Events
Event | 類型 | 描述 | 定義於 |
---|---|---|---|
EVENT_AFTER_ACTION | yii\base\ActionEvent | 在執行控制器動作後立即引發的事件。 | yii\base\Controller |
EVENT_BEFORE_ACTION | yii\base\ActionEvent | 在執行控制器動作前立即引發的事件。 | yii\base\Controller |
Property Details
用於建立模型的場景。
用於更新模型的場景。
Method Details
Defined in: yii\base\Component::__call()
呼叫指定的非類別方法。
此方法將檢查是否有任何附加的行為具有指定的名稱方法,如果有則執行它。
請勿直接呼叫此方法,因為它是一個 PHP 魔術方法,當調用未知方法時將會隱式呼叫。
public mixed __call ( $name, $params ) | ||
$name | string |
方法名稱 |
$params | array |
方法參數 |
return | 混合 |
方法傳回值 |
---|---|---|
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()");
}
public void __clone ( ) |
public function __clone()
{
$this->_events = [];
$this->_eventWildcards = [];
$this->_behaviors = null;
}
Defined in: yii\base\Controller::__construct()
public void __construct ( $id, $module, $config = [] ) | ||
$id | string |
此控制器的 ID。 |
$module | yii\base\Module |
此控制器所屬的模組。 |
$config | array |
將用於初始化物件屬性的名稱-值對。 |
public function __construct($id, $module, $config = [])
{
$this->id = $id;
$this->module = $module;
parent::__construct($config);
}
Defined in: yii\base\Component::__get()
傳回組件屬性的值。
此方法將按以下順序檢查並採取相應措施
- 由 getter 定義的屬性:傳回 getter 結果
- 行為的屬性:傳回行為屬性值
請勿直接呼叫此方法,因為它是一個 PHP 魔術方法,當執行 $value = $component->property;
時將會隱式呼叫。
另請參閱 __set()。
public mixed __get ( $name ) | ||
$name | string |
屬性名稱 |
return | 混合 |
屬性值或行為屬性的值 |
---|---|---|
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);
}
Defined in: yii\base\Component::__isset()
檢查屬性是否已設定,即已定義且非空值。
此方法將按以下順序檢查並採取相應措施
- 由 setter 定義的屬性:傳回屬性是否已設定
- 行為的屬性:傳回屬性是否已設定
- 對於不存在的屬性傳回
false
請勿直接呼叫此方法,因為它是一個 PHP 魔術方法,當執行 isset($component->property)
時將會隱式呼叫。
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;
}
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 | 混合 |
屬性值 |
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);
}
Defined in: yii\base\Component::__unset()
將組件屬性設定為 null。
此方法將按以下順序檢查並採取相應措施
- 由 setter 定義的屬性:將屬性值設定為 null
- 行為的屬性:將屬性值設定為 null
請勿直接呼叫此方法,因為它是一個 PHP 魔術方法,當執行 unset($component->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);
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);
}
為控制器宣告外部動作。
此方法旨在被覆寫,以宣告控制器的外部動作。它應該傳回一個陣列,其中陣列鍵是動作 ID,陣列值是對應的動作類別名稱或動作配置陣列。例如:
return [
'action1' => 'app\components\Action1',
'action2' => [
'class' => 'app\components\Action2',
'property1' => 'value1',
'property2' => 'value2',
],
];
Yii::createObject() 稍後將使用,使用此處提供的配置來建立請求的動作。
public array actions ( ) |
public function actions()
{
return [
'index' => [
'class' => 'yii\rest\IndexAction',
'modelClass' => $this->modelClass,
'checkAccess' => [$this, 'checkAccess'],
],
'view' => [
'class' => 'yii\rest\ViewAction',
'modelClass' => $this->modelClass,
'checkAccess' => [$this, 'checkAccess'],
],
'create' => [
'class' => 'yii\rest\CreateAction',
'modelClass' => $this->modelClass,
'checkAccess' => [$this, 'checkAccess'],
'scenario' => $this->createScenario,
],
'update' => [
'class' => 'yii\rest\UpdateAction',
'modelClass' => $this->modelClass,
'checkAccess' => [$this, 'checkAccess'],
'scenario' => $this->updateScenario,
],
'delete' => [
'class' => 'yii\rest\DeleteAction',
'modelClass' => $this->modelClass,
'checkAccess' => [$this, 'checkAccess'],
],
'options' => [
'class' => 'yii\rest\OptionsAction',
],
];
}
Defined in: yii\rest\Controller::afterAction()
此方法在動作執行後立即調用。
此方法將觸發 EVENT_AFTER_ACTION 事件。此方法的傳回值將用作動作傳回值。
如果您覆寫此方法,您的程式碼應如下所示
public function afterAction($action, $result)
{
$result = parent::afterAction($action, $result);
// your custom code here
return $result;
}
public mixed afterAction ( $action, $result ) | ||
$action | yii\base\Action |
剛執行的動作。 |
$result | 混合 |
動作傳回結果。 |
return | 混合 |
The processed action result. |
---|
public function afterAction($action, $result)
{
$result = parent::afterAction($action, $result);
return $this->serializeData($result);
}
Defined in: yii\web\Controller::asJson()
發送格式化為 JSON 的資料。
此方法是發送格式化為 JSON 的資料的快捷方式。在配置 format 並設定應格式化的 data 後,它將傳回 response 應用程式組件。常見用法如下
return $this->asJson($data);
另請參閱
public yii\web\Response asJson ( $data ) | ||
$data | 混合 |
應格式化的資料。 |
return | yii\web\Response |
A response that is configured to send |
---|
public function asJson($data)
{
$this->response->format = Response::FORMAT_JSON;
$this->response->data = $data;
return $this->response;
}
Defined in: yii\web\Controller::asXml()
發送格式化為 XML 的資料。
此方法是發送格式化為 XML 的資料的快捷方式。在配置 format 並設定應格式化的 data 後,它將傳回 response 應用程式組件。常見用法如下
return $this->asXml($data);
另請參閱
public yii\web\Response asXml ( $data ) | ||
$data | 混合 |
應格式化的資料。 |
return | yii\web\Response |
A response that is configured to send |
---|
public function asXml($data)
{
$this->response->format = Response::FORMAT_XML;
$this->response->data = $data;
return $this->response;
}
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 |
The behavior object |
---|
public function attachBehavior($name, $behavior)
{
$this->ensureBehaviors();
return $this->attachBehaviorInternal($name, $behavior);
}
Defined in: yii\base\Component::attachBehaviors()
將行為列表附加到組件。
每個行為都由其名稱索引,並且應該是一個 yii\base\Behavior 物件、一個指定行為類別的字串,或一個用於建立行為的配置陣列。
另請參閱 attachBehavior()。
public void attachBehaviors ( $behaviors ) | ||
$behaviors | array |
List of behaviors to be attached to the component |
public function attachBehaviors($behaviors)
{
$this->ensureBehaviors();
foreach ($behaviors as $name => $behavior) {
$this->attachBehaviorInternal($name, $behavior);
}
}
Defined in: yii\web\Controller::beforeAction()
此方法在動作執行前立即調用。
此方法將觸發 EVENT_BEFORE_ACTION 事件。此方法的傳回值將決定動作是否應繼續執行。
如果動作不應執行,則應通過提供必要的輸出或重新導向請求在 beforeAction
程式碼內部處理請求。否則,回應將為空。
如果您覆寫此方法,您的程式碼應如下所示
public function beforeAction($action)
{
// your custom code here, if you want the code to run before action filters,
// which are triggered on the [[EVENT_BEFORE_ACTION]] event, e.g. PageCache or AccessControl
if (!parent::beforeAction($action)) {
return false;
}
// other custom code here
return true; // or false to not run the action
}
public boolean beforeAction ( $action ) | ||
$action | yii\base\Action |
The action to be executed. |
return | boolean |
動作是否應繼續執行。 |
---|
public function beforeAction($action)
{
if (parent::beforeAction($action)) {
if ($this->enableCsrfValidation && Yii::$app->getErrorHandler()->exception === null && !$this->request->validateCsrfToken()) {
throw new BadRequestHttpException(Yii::t('yii', 'Unable to verify your data submission.'));
}
return true;
}
return false;
}
Defined in: yii\rest\Controller::behaviors()
傳回此組件應表現為的行為列表。
子類別可以覆寫此方法以指定它們想要表現為的行為。
此方法的傳回值應該是由行為物件或配置組成的陣列,並以行為名稱索引。行為配置可以是指定行為類別的字串,也可以是以下結構的陣列
'behaviorName' => [
'class' => 'BehaviorClass',
'property1' => 'value1',
'property2' => 'value2',
]
請注意,行為類別必須從 yii\base\Behavior 擴展。行為可以使用名稱或匿名附加。當使用名稱作為陣列鍵時,使用此名稱,稍後可以使用 getBehavior() 檢索行為,或使用 detachBehavior() 分離行為。匿名行為無法檢索或分離。
在此方法中宣告的行為將自動(按需)附加到組件。
public array behaviors ( ) | ||
return | array |
行為配置。 |
---|
public function behaviors()
{
return [
'contentNegotiator' => [
'class' => ContentNegotiator::className(),
'formats' => [
'application/json' => Response::FORMAT_JSON,
'application/xml' => Response::FORMAT_XML,
],
],
'verbFilter' => [
'class' => VerbFilter::className(),
'actions' => $this->verbs(),
],
'authenticator' => [
'class' => CompositeAuth::className(),
],
'rateLimiter' => [
'class' => RateLimiter::className(),
],
];
}
Defined in: yii\web\Controller::bindActionParams()
將參數綁定到動作。
當 yii\base\Action 開始使用給定的參數執行時,將調用此方法。此方法將檢查動作所需的參數名稱,並根據需求傳回提供的參數。如果缺少任何參數,將會拋出例外。
public array bindActionParams ( $action, $params ) | ||
$action | yii\base\Action |
The action to be bound with parameters |
$params | array |
要綁定到動作的參數 |
return | array |
The valid parameters that the action can run with. |
---|---|---|
throws | yii\web\BadRequestHttpException |
如果缺少或參數無效。 |
public function bindActionParams($action, $params)
{
if ($action instanceof InlineAction) {
$method = new \ReflectionMethod($this, $action->actionMethod);
} else {
$method = new \ReflectionMethod($action, 'run');
}
$args = [];
$missing = [];
$actionParams = [];
$requestedParams = [];
foreach ($method->getParameters() as $param) {
$name = $param->getName();
if (array_key_exists($name, $params)) {
$isValid = true;
if (PHP_VERSION_ID >= 80000) {
$isArray = ($type = $param->getType()) instanceof \ReflectionNamedType && $type->getName() === 'array';
} else {
$isArray = $param->isArray();
}
if ($isArray) {
$params[$name] = (array)$params[$name];
} elseif (is_array($params[$name])) {
$isValid = false;
} elseif (
PHP_VERSION_ID >= 70000
&& ($type = $param->getType()) !== null
&& method_exists($type, 'isBuiltin')
&& $type->isBuiltin()
&& ($params[$name] !== null || !$type->allowsNull())
) {
$typeName = PHP_VERSION_ID >= 70100 ? $type->getName() : (string)$type;
if ($params[$name] === '' && $type->allowsNull()) {
if ($typeName !== 'string') { // for old string behavior compatibility
$params[$name] = null;
}
} else {
switch ($typeName) {
case 'int':
$params[$name] = filter_var($params[$name], FILTER_VALIDATE_INT, FILTER_NULL_ON_FAILURE);
break;
case 'float':
$params[$name] = filter_var($params[$name], FILTER_VALIDATE_FLOAT, FILTER_NULL_ON_FAILURE);
break;
case 'bool':
$params[$name] = filter_var($params[$name], FILTER_VALIDATE_BOOLEAN, FILTER_NULL_ON_FAILURE);
break;
}
if ($params[$name] === null) {
$isValid = false;
}
}
}
if (!$isValid) {
throw new BadRequestHttpException(
Yii::t('yii', 'Invalid data received for parameter "{param}".', ['param' => $name])
);
}
$args[] = $actionParams[$name] = $params[$name];
unset($params[$name]);
} elseif (
PHP_VERSION_ID >= 70100
&& ($type = $param->getType()) !== null
&& $type instanceof \ReflectionNamedType
&& !$type->isBuiltin()
) {
try {
$this->bindInjectedParams($type, $name, $args, $requestedParams);
} catch (HttpException $e) {
throw $e;
} catch (Exception $e) {
throw new ServerErrorHttpException($e->getMessage(), 0, $e);
}
} elseif ($param->isDefaultValueAvailable()) {
$args[] = $actionParams[$name] = $param->getDefaultValue();
} else {
$missing[] = $name;
}
}
if (!empty($missing)) {
throw new BadRequestHttpException(
Yii::t('yii', 'Missing required parameters: {params}', ['params' => implode(', ', $missing)])
);
}
$this->actionParams = $actionParams;
// We use a different array here, specifically one that doesn't contain service instances but descriptions instead.
if (Yii::$app->requestedParams === null) {
Yii::$app->requestedParams = array_merge($actionParams, $requestedParams);
}
return $args;
}
Defined in: yii\base\Controller::bindInjectedParams()
根據動作方法簽名中的類型和名稱填寫參數。
protected void bindInjectedParams ( ReflectionType $type, $name, &$args, &$requestedParams ) | ||
$type | ReflectionType |
動作參數的反射類型。 |
$name | string |
The name of the parameter. |
$args | array |
動作的參數陣列,此函數可能會向其附加項目。 |
$requestedParams | array |
包含請求參數的陣列,此函數可能會將特定鍵寫入其中。 |
throws | yii\base\ErrorException |
當我們無法載入所需的服務時。 |
---|---|---|
throws | yii\base\InvalidConfigException |
當 DI 配置中存在錯誤時拋出。 |
throws | yii\di\NotInstantiableException |
當定義無法解析為具體的類別時拋出 (例如,介面類型提示),且容器中沒有適當的定義。 |
final protected function bindInjectedParams(\ReflectionType $type, $name, &$args, &$requestedParams)
{
// Since it is not a builtin type it must be DI injection.
$typeName = $type->getName();
if (($component = $this->module->get($name, false)) instanceof $typeName) {
$args[] = $component;
$requestedParams[$name] = 'Component: ' . get_class($component) . " \$$name";
} elseif ($this->module->has($typeName) && ($service = $this->module->get($typeName)) instanceof $typeName) {
$args[] = $service;
$requestedParams[$name] = 'Module ' . get_class($this->module) . " DI: $typeName \$$name";
} elseif (\Yii::$container->has($typeName) && ($service = \Yii::$container->get($typeName)) instanceof $typeName) {
$args[] = $service;
$requestedParams[$name] = "Container DI: $typeName \$$name";
} elseif ($type->allowsNull()) {
$args[] = null;
$requestedParams[$name] = "Unavailable service: $name";
} else {
throw new Exception('Could not load required service: ' . $name);
}
}
定義於: yii\base\Component::canGetProperty()
傳回一個值,指示屬性是否可讀取。
在以下情況下,屬性可以被讀取:
- 類別具有與指定名稱相關聯的 getter 方法(在這種情況下,屬性名稱不區分大小寫);
- 類別具有帶有指定名稱的成員變數 (當
$checkVars
為 true 時); - 附加的行為 (behavior) 具有給定名稱的可讀屬性 (當
$checkBehaviors
為 true 時)。
另請參閱 canSetProperty()。
public boolean canGetProperty ( $name, $checkVars = true, $checkBehaviors = true ) | ||
$name | string |
屬性名稱 |
$checkVars | boolean |
是否將成員變數視為屬性 |
$checkBehaviors | boolean |
是否將行為 (behavior) 的屬性視為此組件的屬性 |
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;
}
定義於: yii\base\Component::canSetProperty()
傳回一個值,指示屬性是否可設定。
在以下情況下,屬性可以被寫入:
- 類別具有與指定名稱相關聯的 setter 方法(在這種情況下,屬性名稱不區分大小寫);
- 類別具有帶有指定名稱的成員變數 (當
$checkVars
為 true 時); - 附加的行為 (behavior) 具有給定名稱的可寫屬性 (當
$checkBehaviors
為 true 時)。
另請參閱 canGetProperty()。
public boolean canSetProperty ( $name, $checkVars = true, $checkBehaviors = true ) | ||
$name | string |
屬性名稱 |
$checkVars | boolean |
是否將成員變數視為屬性 |
$checkBehaviors | boolean |
是否將行為 (behavior) 的屬性視為此組件的屬性 |
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;
}
檢查目前使用者的權限。
應該覆寫此方法,以檢查目前使用者是否具有權限,可以針對指定的資料模型執行指定的操作。如果使用者沒有存取權限,應該拋出 yii\web\ForbiddenHttpException。
public void checkAccess ( $action, $model = null, $params = [] ) | ||
$action | string |
要執行的操作 ID |
$model | object|null |
要存取的模型。如果為 null,表示沒有存取特定的模型。 |
$params | array |
額外的參數 |
throws | yii\web\ForbiddenHttpException |
如果使用者沒有存取權限 |
---|
public function checkAccess($action, $model = null, $params = [])
{
}
::class
。
定義於: yii\base\BaseObject::className()
傳回此類別的完整限定名稱。
public static string className ( ) | ||
return | string |
此類別的完整限定名稱。 |
---|
public static function className()
{
return get_called_class();
}
定義於: yii\base\Controller::createAction()
根據給定的動作 ID 建立一個動作。
此方法首先檢查操作 ID 是否已在 actions() 中宣告。如果是,它將使用該處宣告的配置來建立操作物件。如果不是,它將尋找控制器方法,其名稱格式為 actionXyz
,其中 xyz
是操作 ID。如果找到,將建立並傳回代表該方法的 yii\base\InlineAction。
public yii\base\Action|null createAction ( $id ) | ||
$id | string |
操作 ID。 |
return | yii\base\Action|null |
新建立的操作實例。如果 ID 無法解析為任何操作,則為 Null。 |
---|
public function createAction($id)
{
if ($id === '') {
$id = $this->defaultAction;
}
$actionMap = $this->actions();
if (isset($actionMap[$id])) {
return Yii::createObject($actionMap[$id], [$id, $this]);
}
if (preg_match('/^(?:[a-z0-9_]+-)*[a-z0-9_]+$/', $id)) {
$methodName = 'action' . str_replace(' ', '', ucwords(str_replace('-', ' ', $id)));
if (method_exists($this, $methodName)) {
$method = new \ReflectionMethod($this, $methodName);
if ($method->isPublic() && $method->getName() === $methodName) {
return new InlineAction($id, $this, $methodName);
}
}
}
return null;
}
定義於: yii\base\Component::detachBehavior()
從組件分離行為。
將會調用行為 (behavior) 的 yii\base\Behavior::detach() 方法。
public yii\base\Behavior|null detachBehavior ( $name ) | ||
$name | string |
行為 (behavior) 的名稱。 |
return | yii\base\Behavior|null |
已分離的行為 (behavior)。如果行為不存在,則為 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;
}
定義於: yii\base\Component::detachBehaviors()
從組件分離所有行為。
public void detachBehaviors ( ) |
public function detachBehaviors()
{
$this->ensureBehaviors();
foreach ($this->_behaviors as $name => $behavior) {
$this->detachBehavior($name);
}
}
定義於: 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);
}
}
}
定義於: yii\base\Controller::findLayoutFile()
尋找適用的版面配置檔案。
public string|boolean findLayoutFile ( $view ) | ||
$view | yii\base\View |
用於渲染版型 (layout) 檔案的視圖 (view) 物件。 |
return | string|boolean |
版型檔案路徑,或如果不需要版型則為 false。請參閱 render(),瞭解如何指定此參數。 |
---|---|---|
throws | yii\base\InvalidArgumentException |
如果使用無效的路徑別名來指定版型。 |
public function findLayoutFile($view)
{
$module = $this->module;
$layout = null;
if (is_string($this->layout)) {
$layout = $this->layout;
} elseif ($this->layout === null) {
while ($module !== null && $module->layout === null) {
$module = $module->module;
}
if ($module !== null && is_string($module->layout)) {
$layout = $module->layout;
}
}
if ($layout === null) {
return false;
}
if (strncmp($layout, '@', 1) === 0) {
$file = Yii::getAlias($layout);
} elseif (strncmp($layout, '/', 1) === 0) {
$file = Yii::$app->getLayoutPath() . DIRECTORY_SEPARATOR . substr($layout, 1);
} else {
$file = $module->getLayoutPath() . DIRECTORY_SEPARATOR . $layout;
}
if (pathinfo($file, PATHINFO_EXTENSION) !== '') {
return $file;
}
$path = $file . '.' . $view->defaultExtension;
if ($view->defaultExtension !== 'php' && !is_file($path)) {
$path = $file . '.php';
}
return $path;
}
定義於: yii\base\Component::getBehavior()
傳回指定名稱的行為物件。
public yii\base\Behavior|null getBehavior ( $name ) | ||
$name | string |
行為 (behavior) 名稱 |
return | yii\base\Behavior|null |
行為 (behavior) 物件,如果行為不存在則為 null |
---|
public function getBehavior($name)
{
$this->ensureBehaviors();
return isset($this->_behaviors[$name]) ? $this->_behaviors[$name] : null;
}
定義於: yii\base\Component::getBehaviors()
傳回附加到此組件的所有行為。
public yii\base\Behavior[] getBehaviors ( ) | ||
return | yii\base\Behavior[] |
附加到此組件的行為 (behavior) 列表 |
---|
public function getBehaviors()
{
$this->ensureBehaviors();
return $this->_behaviors;
}
public yii\base\Module[] getModules ( ) | ||
return | yii\base\Module[] |
此控制器所在的所有祖先模組。 |
---|
public function getModules()
{
$modules = [$this->module];
$module = $this->module;
while ($module->module !== null) {
array_unshift($modules, $module->module);
$module = $module->module;
}
return $modules;
}
定義於: yii\base\Controller::getRoute()
傳回目前請求的路徑。
public string getRoute ( ) | ||
return | string |
目前請求的路徑(模組 ID、控制器 ID 和動作 ID)。 |
---|
public function getRoute()
{
return $this->action !== null ? $this->action->getUniqueId() : $this->getUniqueId();
}
定義於: yii\base\Controller::getUniqueId()
傳回控制器的唯一 ID。
public string getUniqueId ( ) | ||
return | string |
以模組 ID 為前綴的控制器 ID(如果有的話)。 |
---|
public function getUniqueId()
{
return $this->module instanceof Application ? $this->id : $this->module->getUniqueId() . '/' . $this->id;
}
定義於: yii\base\Controller::getView()
傳回可用於呈現視圖或視圖檔案的視圖物件。
render()、renderPartial() 和 renderFile() 方法將使用此視圖 (view) 物件來實作實際的視圖渲染。如果未設定,預設為 "view" 應用程式組件。
public yii\base\View|yii\web\View getView ( ) | ||
return | yii\base\View|yii\web\View |
可用於呈現視圖或視圖檔案的視圖物件。 |
---|
public function getView()
{
if ($this->_view === null) {
$this->_view = Yii::$app->getView();
}
return $this->_view;
}
定義於: yii\base\Controller::getViewPath()
傳回包含此控制器視圖檔案的目錄。
public string getViewPath ( ) | ||
return | string |
包含此控制器視圖檔案的目錄。 |
---|
public function getViewPath()
{
if ($this->_viewPath === null) {
$this->_viewPath = $this->module->getViewPath() . DIRECTORY_SEPARATOR . $this->id;
}
return $this->_viewPath;
}
定義於: yii\web\Controller::goBack()
將瀏覽器重新導向到上次訪問的頁面。
您可以在操作 (action) 中使用此方法,直接傳回 yii\web\Response
// stop executing this action and redirect to last visited page
return $this->goBack();
為了使此函數正常運作,您必須事先在適當的位置 設定返回 URL。
public yii\web\Response goBack ( $defaultUrl = null ) | ||
$defaultUrl | string|array|null |
如果先前未設定,則為預設返回 URL。如果此值為 null 且先前未設定返回 URL,則將重新導向至 yii\web\Application::$homeUrl。請參閱 yii\web\User::setReturnUrl(),瞭解可接受的 URL 格式。 |
return | yii\web\Response |
目前的 response 物件 |
---|
public function goBack($defaultUrl = null)
{
return $this->response->redirect(Yii::$app->getUser()->getReturnUrl($defaultUrl));
}
定義於: yii\web\Controller::goHome()
將瀏覽器重新導向到首頁。
您可以在操作 (action) 中使用此方法,直接傳回 yii\web\Response
// stop executing this action and redirect to home page
return $this->goHome();
public yii\web\Response goHome ( ) | ||
return | yii\web\Response |
目前的 response 物件 |
---|
public function goHome()
{
return $this->response->redirect(Yii::$app->getHomeUrl());
}
定義於: yii\base\Component::hasEventHandlers()
傳回一個值,指示是否有名稱事件附加任何處理常式。
public boolean hasEventHandlers ( $name ) | ||
$name | string |
事件名稱 |
return | boolean |
是否有任何處理器 (handler) 附加到事件。 |
---|
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);
}
定義於: yii\base\Component::hasMethod()
傳回一個值,指示是否已定義方法。
在以下情況下,方法被定義:
- 類別具有帶有指定名稱的方法
- 附加的行為 (behavior) 具有給定名稱的方法 (當
$checkBehaviors
為 true 時)。
public boolean hasMethod ( $name, $checkBehaviors = true ) | ||
$name | string |
屬性名稱 |
$checkBehaviors | boolean |
是否將行為 (behavior) 的方法視為此組件的方法 |
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;
}
定義於: yii\base\Component::hasProperty()
傳回一個值,指示是否為此組件定義了屬性。
在以下情況下,屬性被定義:
- 類別具有與指定名稱相關聯的 getter 或 setter 方法(在這種情況下,屬性名稱不區分大小寫);
- 類別具有帶有指定名稱的成員變數 (當
$checkVars
為 true 時); - 附加的行為 (behavior) 具有給定名稱的屬性 (當
$checkBehaviors
為 true 時)。
另請參閱
public boolean hasProperty ( $name, $checkVars = true, $checkBehaviors = true ) | ||
$name | string |
屬性名稱 |
$checkVars | boolean |
是否將成員變數視為屬性 |
$checkBehaviors | boolean |
是否將行為 (behavior) 的屬性視為此組件的屬性 |
return | boolean |
屬性是否已定義 |
---|
public function hasProperty($name, $checkVars = true, $checkBehaviors = true)
{
return $this->canGetProperty($name, $checkVars, $checkBehaviors) || $this->canSetProperty($name, false, $checkBehaviors);
}
初始化物件。
在物件使用給定的配置初始化後,此方法會在建構函式的結尾被調用。
public void init ( ) |
public function init()
{
parent::init();
if ($this->modelClass === null) {
throw new InvalidConfigException('The "modelClass" property must be set.');
}
}
定義於: yii\base\Component::off()
從此組件分離現有的事件處理常式。
此方法與 on() 相反。
注意:如果為事件名稱傳遞了萬用字元模式,則只會移除使用此萬用字元註冊的處理器 (handler),而使用與此萬用字元匹配的純名稱註冊的處理器將保持不變。
另請參閱 on()。
public boolean off ( $name, $handler = null ) | ||
$name | string |
事件名稱 |
$handler | callable|null |
要移除的事件處理器 (handler)。如果為 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;
}
將事件處理常式附加到事件。
事件處理器 (handler) 必須是有效的 PHP 回呼 (callback)。以下是一些範例
function ($event) { ... } // anonymous function
[$object, 'handleClick'] // $object->handleClick()
['Page', 'handleClick'] // Page::handleClick()
'handleClick' // global function handleClick()
事件處理器 (handler) 必須使用以下簽名 (signature) 定義:
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 |
事件處理器 (handler) |
$data | 混合 |
事件觸發時要傳遞給事件處理器 (handler) 的資料。當調用事件處理器時,可以透過 yii\base\Event::$data 存取此資料。 |
$append | boolean |
是否將新的事件處理器 (handler) 附加到現有處理器列表的末尾。如果為 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]);
}
}
定義於: yii\web\Controller::redirect()
將瀏覽器重新導向到指定的 URL。
此方法是 yii\web\Response::redirect() 的快捷方式。
您可以在操作 (action) 中使用它,直接傳回 yii\web\Response
// stop executing this action and redirect to login page
return $this->redirect(['login']);
public yii\web\Response redirect ( $url, $statusCode = 302 ) | ||
$url | string|array |
要重新導向到的 URL。可以是以下格式之一:
任何以單個正斜線 "/" 開頭的相對 URL 都將轉換為絕對 URL,方法是在其前面加上當前請求的主機資訊。 |
$statusCode | integer |
HTTP 狀態碼。預設為 302。有關 HTTP 狀態碼的詳細資訊,請參閱 https://tools.ietf.org/html/rfc2616#section-10 |
return | yii\web\Response |
目前的 response 物件 |
---|
public function redirect($url, $statusCode = 302)
{
// calling Url::to() here because Response::redirect() modifies route before calling Url::to()
return $this->response->redirect(Url::to($url), $statusCode);
}
定義於: yii\web\Controller::refresh()
重新整理目前頁面。
此方法是 yii\web\Response::refresh() 的快捷方式。
您可以在操作 (action) 中使用它,直接傳回 yii\web\Response
// stop executing this action and refresh the current page
return $this->refresh();
public yii\web\Response refresh ( $anchor = '' ) | ||
$anchor | string |
應該附加到重新導向 URL 的錨點 (anchor)。預設為空字串。如果您想指定錨點,請確保錨點以 '#' 開頭。 |
return | yii\web\Response |
response 物件本身 |
---|
public function refresh($anchor = '')
{
return $this->response->redirect($this->request->getUrl() . $anchor);
}
定義於: yii\base\Controller::render()
呈現視圖並在可用時套用版面配置。
要渲染的視圖 (view) 可以使用以下格式之一指定:
- 路徑別名 (例如 "@app/views/site/index");
- 應用程式內的絕對路徑 (例如 "//site/index"):視圖名稱以雙斜線開頭。實際的視圖檔案將在應用程式的 視圖路徑 下尋找。
- 模組內的絕對路徑 (例如 "/site/index"):視圖名稱以單斜線開頭。實際的視圖檔案將在 $module 的 視圖路徑 下尋找。
- 相對路徑 (例如 "index"):實際的視圖檔案將在 $viewPath 下尋找。
為了確定應套用哪個版型,將執行以下兩個步驟
- 在第一步中,它會判斷版型名稱和上下文模組
- 如果 $layout 指定為字串,則使用它作為版型名稱,並使用 $module 作為上下文模組;
- 如果 $layout 為 null,則搜尋此控制器的所有上層模組,並找到第一個 layout 不為 null 的模組。版型和對應的模組將分別用作版型名稱和上下文模組。如果找不到這樣的模組,或者對應的版型不是字串,它將返回 false,表示沒有適用的版型。
- 在第二步中,它會根據先前找到的版型名稱和上下文模組來確定實際的版型檔案。版型名稱可以是
- 路徑別名 (例如 "@app/views/layouts/main");
- 絕對路徑 (例如 "/main"):版型名稱以斜線開頭。實際的版型檔案將在應用程式的 版型路徑 下尋找;
- 相對路徑 (例如 "main"):實際的版型檔案將在上下文模組的 版型路徑 下尋找。
如果版型名稱不包含副檔名,它將使用預設的 .php
。
public string render ( $view, $params = [] ) | ||
$view | string |
視圖名稱。 |
$params | array |
應該在視圖中提供的參數 (名稱-值 組)。這些參數在版型中將不可用。 |
return | string |
渲染結果。 |
---|---|---|
throws | yii\base\InvalidArgumentException |
如果視圖檔案或版型檔案不存在。 |
public function render($view, $params = [])
{
$content = $this->getView()->render($view, $params, $this);
return $this->renderContent($content);
}
定義於: yii\web\Controller::renderAjax()
回應 AJAX 請求呈現視圖。
此方法類似於 renderPartial(),除了它會將在視圖中註冊的 JS/CSS 腳本和檔案注入到渲染結果中。因此,您應該使用此方法而不是 renderPartial() 來渲染視圖以回應 AJAX 請求。
public string renderAjax ( $view, $params = [] ) | ||
$view | string |
視圖名稱。請參考 render() 了解如何指定視圖名稱。 |
$params | array |
應該在視圖中提供的參數 (名稱-值 組)。 |
return | string |
渲染結果。 |
---|
public function renderAjax($view, $params = [])
{
return $this->getView()->renderAjax($view, $params, $this);
}
定義於: yii\base\Controller::renderContent()
通過套用版面配置呈現靜態字串。
public string renderContent ( $content ) | ||
$content | string |
正在渲染的靜態字串 |
return | string |
具有給定靜態字串作為 |
---|
public function renderContent($content)
{
$layoutFile = $this->findLayoutFile($this->getView());
if ($layoutFile !== false) {
return $this->getView()->renderFile($layoutFile, ['content' => $content], $this);
}
return $content;
}
定義於: yii\base\Controller::renderFile()
呈現視圖檔案。
public string renderFile ( $file, $params = [] ) | ||
$file | string |
要渲染的視圖檔案。這可以是檔案路徑或路徑別名。 |
$params | array |
應該在視圖中提供的參數 (名稱-值 組)。 |
return | string |
渲染結果。 |
---|---|---|
throws | yii\base\InvalidArgumentException |
如果視圖檔案不存在。 |
public function renderFile($file, $params = [])
{
return $this->getView()->renderFile($file, $params, $this);
}
public string renderPartial ( $view, $params = [] ) | ||
$view | string |
視圖名稱。請參考 render() 了解如何指定視圖名稱。 |
$params | array |
應該在視圖中提供的參數 (名稱-值 組)。 |
return | string |
渲染結果。 |
---|---|---|
throws | yii\base\InvalidArgumentException |
如果視圖檔案不存在。 |
public function renderPartial($view, $params = [])
{
return $this->getView()->render($view, $params, $this);
}
定義於: yii\base\Controller::run()
執行以路徑形式指定的請求。
路由可以是此控制器內動作的 ID,或由模組 ID、控制器 ID 和動作 ID 組成的完整路由。如果路由以斜線 '/' 開頭,則路由的解析將從應用程式開始;否則,它將從此控制器的父模組開始。
另請參閱 runAction()。
public mixed run ( $route, $params = [] ) | ||
$route | string |
要處理的路由,例如 'view'、'comment/view'、'/admin/comment/view'。 |
$params | array |
要傳遞給動作的參數。 |
return | 混合 |
動作的結果。 |
---|
public function run($route, $params = [])
{
$pos = strpos($route, '/');
if ($pos === false) {
return $this->runAction($route, $params);
} elseif ($pos > 0) {
return $this->module->runAction($route, $params);
}
return Yii::$app->runAction(ltrim($route, '/'), $params);
}
定義於: yii\base\Controller::runAction()
使用指定的動作 ID 和參數在此控制器中執行動作。
如果動作 ID 為空,該方法將使用 $defaultAction。
另請參閱 createAction()。
public mixed runAction ( $id, $params = [] ) | ||
$id | string |
要執行的動作 ID。 |
$params | array |
要傳遞給動作的參數 (名稱-值 組)。 |
return | 混合 |
動作的結果。 |
---|---|---|
throws | yii\base\InvalidRouteException |
如果請求的動作 ID 無法成功解析為動作。 |
public function runAction($id, $params = [])
{
$action = $this->createAction($id);
if ($action === null) {
throw new InvalidRouteException('Unable to resolve the request: ' . $this->getUniqueId() . '/' . $id);
}
Yii::debug('Route to run: ' . $action->getUniqueId(), __METHOD__);
if (Yii::$app->requestedAction === null) {
Yii::$app->requestedAction = $action;
}
$oldAction = $this->action;
$this->action = $action;
$modules = [];
$runAction = true;
// call beforeAction on modules
foreach ($this->getModules() as $module) {
if ($module->beforeAction($action)) {
array_unshift($modules, $module);
} else {
$runAction = false;
break;
}
}
$result = null;
if ($runAction && $this->beforeAction($action)) {
// run the action
$result = $action->runWithParams($params);
$result = $this->afterAction($action, $result);
// call afterAction on modules
foreach ($modules as $module) {
/* @var $module Module */
$result = $module->afterAction($action, $result);
}
}
if ($oldAction !== null) {
$this->action = $oldAction;
}
return $result;
}
定義於: yii\rest\Controller::serializeData()
序列化指定的資料。
預設實作將基於 $serializer 給定的配置建立序列化器。然後它使用序列化器來序列化給定的資料。
protected mixed serializeData ( $data ) | ||
$data | 混合 |
要被序列化的資料 |
return | 混合 |
序列化後的資料。 |
---|
protected function serializeData($data)
{
return Yii::createObject($this->serializer)->serialize($data);
}
定義於: yii\base\Controller::setView()
設定此控制器要使用的視圖物件。
public void setView ( $view ) | ||
$view | yii\base\View|yii\web\View |
可用於呈現視圖或視圖檔案的視圖物件。 |
public function setView($view)
{
$this->_view = $view;
}
定義於: yii\base\Controller::setViewPath()
設定包含視圖檔案的目錄。
public void setViewPath ( $path ) | ||
$path | string |
視圖檔案的根目錄。 |
throws | yii\base\InvalidArgumentException |
如果目錄無效 |
---|
public function setViewPath($path)
{
$this->_viewPath = Yii::getAlias($path);
}
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);
}
宣告允許的 HTTP 動詞。
請參考 yii\filters\VerbFilter::$actions 了解如何宣告允許的動詞。
protected array verbs ( ) | ||
return | array |
允許的 HTTP 動詞。 |
---|
protected function verbs()
{
return [
'index' => ['GET', 'HEAD'],
'view' => ['GET', 'HEAD'],
'create' => ['POST'],
'update' => ['PUT', 'PATCH'],
'delete' => ['DELETE'],
];
}
註冊 或 登入 以便評論。