0 關注者

類別 yii\rest\Controller

繼承yii\rest\Controller » yii\web\Controller » yii\base\Controller » yii\base\Component » yii\base\BaseObject
實作yii\base\Configurable, yii\base\ViewContextInterface
子類別yii\rest\ActiveController
自版本起可用2.0
原始碼 https://github.com/yiisoft/yii2/blob/master/framework/rest/Controller.php

Controller 是 RESTful API 控制器類別的基底類別。

Controller 在 RESTful API 請求處理週期中實作以下步驟

  1. 解析回應格式 (請參閱 yii\filters\ContentNegotiator);
  2. 驗證請求方法 (請參閱 verbs())。
  3. 驗證使用者身分 (請參閱 yii\filters\auth\AuthInterface);
  4. 速率限制 (請參閱 yii\filters\RateLimiter);
  5. 格式化回應資料 (請參閱 serializeData())。

關於控制器的更多詳細資訊和使用方式,請參閱 REST 控制器指南文章

公有屬性

隱藏繼承的屬性

屬性 類型 描述 定義於
$action yii\base\Action|null 目前正在執行的動作。 yii\base\Controller
$actionParams array 綁定到目前動作的參數。 yii\web\Controller
$behaviors yii\base\Behavior[] 附加到此組件的行為列表。 yii\base\Component
$defaultAction string 當請求中未指定動作 ID 時,使用的動作 ID。 yii\base\Controller
$enableCsrfValidation boolean 是否為此控制器中的動作啟用 CSRF 驗證。 yii\rest\Controller
$id string 此控制器的 ID。 yii\base\Controller
$layout string|null|false 要應用於此控制器視圖的版面配置名稱。 yii\base\Controller
$module yii\base\Module 此控制器所屬的模組。 yii\base\Controller
$modules yii\base\Module[] 此控制器所位於的所有祖先模組。 yii\base\Controller
$request yii\base\Request|array|string 請求。 yii\base\Controller
$response yii\base\Response|array|string 回應。 yii\base\Controller
$route string 目前請求的路由 (模組 ID、控制器 ID 和動作 ID)。 yii\base\Controller
$serializer string|array 用於建立序列化器以格式化回應資料的配置。 yii\rest\Controller
$uniqueId string 以模組 ID (如果有的話) 作為前綴的控制器 ID。 yii\base\Controller
$view yii\base\View|yii\web\View 可用於渲染視圖或視圖檔案的視圖物件。 yii\base\Controller
$viewPath string 此控制器視圖檔案所在的目錄。 yii\base\Controller

公共方法

隱藏繼承的方法

方法 描述 定義於
__call() 呼叫未定義為類別方法的具名方法。 yii\base\Component
__clone() 在透過複製現有物件建立新物件後,會呼叫此方法。 yii\base\Component
__construct() yii\base\Controller
__get() 傳回組件屬性的值。 yii\base\Component
__isset() 檢查屬性是否已設定,亦即已定義且非 null。 yii\base\Component
__set() 設定組件屬性的值。 yii\base\Component
__unset() 將組件屬性設定為 null。 yii\base\Component
actions() 宣告控制器的外部動作。 yii\base\Controller
afterAction() 此方法會在動作執行後立即調用。 yii\rest\Controller
asJson() 以 JSON 格式傳送資料。 yii\web\Controller
asXml() 以 XML 格式傳送資料。 yii\web\Controller
attachBehavior() 將行為附加到此組件。 yii\base\Component
attachBehaviors() 將行為列表附加到組件。 yii\base\Component
beforeAction() 此方法會在動作執行前立即調用。 yii\web\Controller
behaviors() 傳回此組件應表現為的行為列表。 yii\rest\Controller
bindActionParams() 將參數綁定到動作。 yii\web\Controller
canGetProperty() 傳回一個值,指示是否可以讀取屬性。 yii\base\Component
canSetProperty() 傳回一個值,指示是否可以設定屬性。 yii\base\Component
className() 傳回此類別的完整限定名稱。 yii\base\BaseObject
createAction() 根據給定的動作 ID 建立動作。 yii\base\Controller
detachBehavior() 從組件分離行為。 yii\base\Component
detachBehaviors() 從組件分離所有行為。 yii\base\Component
ensureBehaviors() 確保在 behaviors() 中宣告的行為已附加到此組件。 yii\base\Component
findLayoutFile() 尋找適用的版面配置檔案。 yii\base\Controller
getBehavior() 傳回具名的行為物件。 yii\base\Component
getBehaviors() 傳回附加到此組件的所有行為。 yii\base\Component
getModules() 傳回此控制器的所有祖先模組。 yii\base\Controller
getRoute() 傳回當前請求的路徑。 yii\base\Controller
getUniqueId() 傳回控制器的唯一 ID。 yii\base\Controller
getView() 傳回可用於渲染視圖或視圖檔案的視圖物件。 yii\base\Controller
getViewPath() 傳回此控制器視圖檔案所在的目錄。 yii\base\Controller
goBack() 將瀏覽器重新導向到最後瀏覽的頁面。 yii\web\Controller
goHome() 將瀏覽器重新導向到首頁。 yii\web\Controller
hasEventHandlers() 傳回一個值,指示是否有任何處理常式附加到具名事件。 yii\base\Component
hasMethod() 傳回一個值,指示是否已定義方法。 yii\base\Component
hasProperty() 傳回一個值,指示是否為此組件定義了屬性。 yii\base\Component
init() 初始化物件。 yii\base\Controller
off() 從此組件分離現有的事件處理常式。 yii\base\Component
on() 將事件處理常式附加到事件。 yii\base\Component
redirect() 將瀏覽器重新導向到指定的 URL。 yii\web\Controller
refresh() 重新整理目前頁面。 yii\web\Controller
render() 渲染視圖並在可用時套用版面配置。 yii\base\Controller
renderAjax() 回應 AJAX 請求渲染視圖。 yii\web\Controller
renderContent() 透過套用版面配置渲染靜態字串。 yii\base\Controller
renderFile() 渲染視圖檔案。 yii\base\Controller
renderPartial() 渲染視圖但不套用版面配置。 yii\base\Controller
run() 執行以路徑形式指定的請求。 yii\base\Controller
runAction() 使用指定的動作 ID 和參數在此控制器中執行動作。 yii\base\Controller
setView() 設定此控制器要使用的視圖物件。 yii\base\Controller
setViewPath() 設定包含視圖檔案的目錄。 yii\base\Controller
trigger() 觸發事件。 yii\base\Component

保護方法

隱藏繼承的方法

方法 描述 定義於
bindInjectedParams() 根據動作方法簽章中的類型和名稱填寫參數。 yii\base\Controller
serializeData() 序列化指定的資料。 yii\rest\Controller
verbs() 宣告允許的 HTTP 動詞。 yii\rest\Controller

事件

隱藏繼承的事件

事件 類型 描述 定義於
EVENT_AFTER_ACTION yii\base\ActionEvent 在執行控制器動作後立即引發的事件。 yii\base\Controller
EVENT_BEFORE_ACTION yii\base\ActionEvent 在執行控制器動作前立即引發的事件。 yii\base\Controller

屬性詳情

隱藏繼承的屬性

$enableCsrfValidation 公共屬性

是否為此控制器中的動作啟用 CSRF 驗證。僅當此屬性和 yii\web\Request::$enableCsrfValidation 都為 true 時,才會啟用 CSRF 驗證。

$serializer 公共屬性

用於建立序列化器以格式化回應資料的配置。

public string|array $serializer 'yii\rest\Serializer'

方法詳情

隱藏繼承的方法

__call() 公共方法

定義於: 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() 公共方法

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

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

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

public void __clone ( )

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

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

            
__get() 公共方法

定義於: 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() 公共方法

定義於: 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() 公共方法

定義於: 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() 公共方法

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

            
actions() 公共方法

定義於: yii\base\Controller::actions()

宣告控制器的外部動作。

此方法旨在被覆寫,以宣告控制器的外部動作。它應傳回一個陣列,其中陣列鍵為動作 ID,而陣列值為對應的動作類別名稱或動作配置陣列。例如:

return [
    'action1' => 'app\components\Action1',
    'action2' => [
        'class' => 'app\components\Action2',
        'property1' => 'value1',
        'property2' => 'value2',
    ],
];

Yii::createObject() 將在稍後用於使用此處提供的配置建立請求的動作。

public array actions ( )

                public function actions()
{
    return [];
}

            
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 mixed

動作傳回結果。

return mixed

已處理的動作結果。

                public function afterAction($action, $result)
{
    $result = parent::afterAction($action, $result);
    return $this->serializeData($result);
}

            
asJson() 公共方法 (自版本 2.0.11 起可用)

定義於: yii\web\Controller::asJson()

以 JSON 格式傳送資料。

此方法是以 JSON 格式傳送資料的捷徑。它將在配置 format 並設定應格式化的 data 後,傳回 response 應用程式組件。常見用法如下:

return $this->asJson($data);

另請參閱

public yii\web\Response asJson ( $data )
$data mixed

應格式化的資料。

return yii\web\Response

配置為以 JSON 格式傳送 $data 的回應。

                public function asJson($data)
{
    $this->response->format = Response::FORMAT_JSON;
    $this->response->data = $data;
    return $this->response;
}

            
asXml() 公共方法 (自版本 2.0.11 起可用)

定義於: yii\web\Controller::asXml()

以 XML 格式傳送資料。

此方法是以 XML 格式傳送資料的捷徑。它將在配置 format 並設定應格式化的 data 後,傳回 response 應用程式組件。常見用法如下:

return $this->asXml($data);

另請參閱

public yii\web\Response asXml ( $data )
$data mixed

應格式化的資料。

return yii\web\Response

配置為以 XML 格式傳送 $data 的回應。

                public function asXml($data)
{
    $this->response->format = Response::FORMAT_XML;
    $this->response->data = $data;
    return $this->response;
}

            
attachBehavior() 公共方法

定義於: 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() 公共方法

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

            
beforeAction() 公共方法

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

要執行的動作。

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

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

            
bindActionParams() 公共方法

定義於: yii\web\Controller::bindActionParams()

將參數綁定到動作。

yii\base\Action 開始使用給定參數執行時,將會調用此方法。此方法將檢查動作所需的參數名稱,並根據需求傳回提供的參數。如果有任何遺失的參數,將會擲回例外。

public array bindActionParams ( $action, $params )
$action yii\base\Action

要與參數綁定的動作

$params array

要綁定到動作的參數

return array

動作可以執行的有效參數。

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

            
bindInjectedParams() 保護方法 (自版本 2.0.36 起可用)

定義於: yii\base\Controller::bindInjectedParams()

根據動作方法簽章中的類型和名稱填寫參數。

protected void bindInjectedParams ( ReflectionType $type, $name, &$args, &$requestedParams )
$type ReflectionType

動作參數的反射類型。

$name string

參數的名稱。

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

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

            
createAction() 公共方法

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

            
detachBehavior() public method

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

            
detachBehaviors() public method

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

從組件分離所有行為。

public void detachBehaviors ( )

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

            
ensureBehaviors() public method

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

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

public void ensureBehaviors ( )

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

            
findLayoutFile() public method

定義於: yii\base\Controller::findLayoutFile()

尋找適用的版面配置檔案。

public string|boolean findLayoutFile ( $view )
$view yii\base\View

要渲染版型檔案的 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;
}

            
getBehavior() public method

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

傳回具名的行為物件。

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

Behavior 名稱

return yii\base\Behavior|null

Behavior 物件,如果 behavior 不存在,則為 null

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

            
getBehaviors() public method

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

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

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

附加到此組件的 behavior 列表

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

            
getModules() public method

定義於: yii\base\Controller::getModules()

傳回此控制器的所有祖先模組。

陣列中的第一個模組是最外層的模組(即應用程式實例),而最後一個是最內層的模組。

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

            
getRoute() public method

定義於: yii\base\Controller::getRoute()

傳回當前請求的路徑。

public string getRoute ( )
return string

目前請求的路由 (模組 ID、控制器 ID 和動作 ID)。

                public function getRoute()
{
    return $this->action !== null ? $this->action->getUniqueId() : $this->getUniqueId();
}

            
getUniqueId() public method

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

            
getView() public method

定義於: yii\base\Controller::getView()

傳回可用於渲染視圖或視圖檔案的視圖物件。

render()renderPartial()renderFile() 方法將使用此 view 物件來實作實際的 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;
}

            
getViewPath() public method

定義於: yii\base\Controller::getViewPath()

傳回此控制器視圖檔案所在的目錄。

預設實作會傳回以控制器 $id 命名的目錄,該目錄位於 $module$viewPath 目錄下。

public string getViewPath ( )
return string

此控制器視圖檔案所在的目錄。

                public function getViewPath()
{
    if ($this->_viewPath === null) {
        $this->_viewPath = $this->module->getViewPath() . DIRECTORY_SEPARATOR . $this->id;
    }
    return $this->_viewPath;
}

            
goBack() public method

定義於: yii\web\Controller::goBack()

將瀏覽器重新導向到最後瀏覽的頁面。

您可以在動作中使用此方法,方法是直接傳回 yii\web\Response

// stop executing this action and redirect to last visited page
return $this->goBack();

為了使此功能正常運作,您必須事先在適當的位置 設定返回 URL

另請參閱 yii\web\User::getReturnUrl()

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

            
goHome() public method

定義於: yii\web\Controller::goHome()

將瀏覽器重新導向到首頁。

您可以在動作中使用此方法,方法是直接傳回 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());
}

            
hasEventHandlers() public method

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

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

public boolean hasEventHandlers ( $name )
$name string

事件名稱

return boolean

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

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

            
hasMethod() public method

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

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

如果符合以下條件,則定義了方法:

  • 類別具有具有指定名稱的方法
  • 附加的 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;
}

            
hasProperty() public method

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

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

return boolean

是否已定義屬性

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

            
init() public method (available since version 2.0.36)

定義於: yii\base\Controller::init()

初始化物件。

在物件使用給定配置初始化後,此方法會在建構函式的結尾被調用。

public void init ( )

                public function init()
{
    parent::init();
    $this->request = Instance::ensure($this->request, Request::className());
    $this->response = Instance::ensure($this->response, Response::className());
}

            
off() public method

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

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

此方法與 on() 相反。

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

另請參閱 on()

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

事件名稱

$handler callable|null

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

return boolean

如果找到並分離處理常式

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

            
on() public method

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

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

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

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

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

function ($event)

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

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

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

另請參閱 off()

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

事件名稱

$handler 可調用 (callable)

事件處理常式

$data mixed

事件觸發時要傳遞給事件處理常式的資料。當調用事件處理常式時,可以透過 yii\base\Event::$data 存取此資料。

$append boolean

是否將新的事件處理常式附加到現有處理常式列表的末尾。如果為 false,則新的處理常式將插入到現有處理常式列表的開頭。

                public function on($name, $handler, $data = null, $append = true)
{
    $this->ensureBehaviors();
    if (strpos($name, '*') !== false) {
        if ($append || empty($this->_eventWildcards[$name])) {
            $this->_eventWildcards[$name][] = [$handler, $data];
        } else {
            array_unshift($this->_eventWildcards[$name], [$handler, $data]);
        }
        return;
    }
    if ($append || empty($this->_events[$name])) {
        $this->_events[$name][] = [$handler, $data];
    } else {
        array_unshift($this->_events[$name], [$handler, $data]);
    }
}

            
redirect() public method

定義於: yii\web\Controller::redirect()

將瀏覽器重新導向到指定的 URL。

此方法是 yii\web\Response::redirect() 的快捷方式。

您可以在動作中使用它,方法是直接傳回 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 的字串 (例如 "https://example.com")
  • 表示 URL 別名的字串 (例如 "@example.com")
  • 格式為 [$route, ...name-value pairs...] 的陣列 (例如 ['site/index', 'ref' => 1])。yii\helpers\Url::to() 將用於將陣列轉換為 URL。

任何以單個正斜線 "/" 開頭的相對 URL 都將轉換為絕對 URL,方法是在其前面加上當前請求的主機資訊。

$statusCode 整數

HTTP 狀態碼。預設值為 302。請參閱 https://tools.ietf.org/html/rfc2616#section-10 了解有關 HTTP 狀態碼的詳細資訊

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

            
refresh() public method

定義於: yii\web\Controller::refresh()

重新整理目前頁面。

此方法是 yii\web\Response::refresh() 的快捷方式。

您可以在動作中使用它,方法是直接傳回 yii\web\Response

// stop executing this action and refresh the current page
return $this->refresh();
public yii\web\Response refresh ( $anchor '' )
$anchor string

應該附加到重新導向 URL 的錨點。預設為空字串。如果要指定錨點,請確保錨點以 '#' 開頭。

return yii\web\Response

response 物件本身

                public function refresh($anchor = '')
{
    return $this->response->redirect($this->request->getUrl() . $anchor);
}

            
render() public method

定義於: yii\base\Controller::render()

渲染視圖並在可用時套用版面配置。

要渲染的 view 可以使用以下格式之一指定

  • 路徑別名 (例如 "@app/views/site/index");
  • 應用程式內的絕對路徑 (例如 "//site/index"):view 名稱以雙斜線開頭。實際的 view 檔案將在應用程式的 view 路徑 下尋找。
  • 模組內的絕對路徑 (例如 "/site/index"):view 名稱以單斜線開頭。實際的 view 檔案將在 $moduleview 路徑 下尋找。
  • 相對路徑 (例如 "index"):實際的 view 檔案將在 $viewPath 下尋找。

為了確定應套用哪個版型,將執行以下兩個步驟

  1. 在第一步中,它確定版型名稱和上下文模組
  • 如果 $layout 指定為字串,則將其用作版型名稱,並將 $module 用作上下文模組;
  • 如果 $layout 為 null,則搜尋此控制器的所有上層模組,並找到第一個 layout 不為 null 的模組。版型和對應的模組分別用作版型名稱和上下文模組。如果找不到此類模組,或者對應的版型不是字串,則會傳回 false,表示沒有適用的版型。
  1. 在第二步中,它根據先前找到的版型名稱和上下文模組確定實際的版型檔案。版型名稱可以是
  • 路徑別名 (例如 "@app/views/layouts/main");
  • 絕對路徑 (例如 "/main"):版型名稱以斜線開頭。實際的版型檔案將在應用程式的 版型路徑 下尋找;
  • 相對路徑 (例如 "main"):實際的版型檔案將在上下文模組的 版型路徑 下尋找。

如果版型名稱不包含檔案副檔名,它將使用預設的 .php

public string render ( $view, $params = [] )
$view string

View 名稱。

$params array

應在 view 中提供的參數(名稱-值對)。這些參數在版型中不可用。

return string

渲染結果。

throws yii\base\InvalidArgumentException

如果 view 檔案或版型檔案不存在。

                public function render($view, $params = [])
{
    $content = $this->getView()->render($view, $params, $this);
    return $this->renderContent($content);
}

            
renderAjax() public method

定義於: yii\web\Controller::renderAjax()

回應 AJAX 請求渲染視圖。

此方法與 renderPartial() 類似,不同之處在於它會將使用 view 註冊的 JS/CSS 腳本和檔案注入到渲染結果中。因此,您應該使用此方法而不是 renderPartial() 來渲染 view 以回應 AJAX 請求。

public string renderAjax ( $view, $params = [] )
$view string

View 名稱。請參閱 render() 了解如何指定 view 名稱。

$params array

應在 view 中提供的參數(名稱-值對)。

return string

渲染結果。

                public function renderAjax($view, $params = [])
{
    return $this->getView()->renderAjax($view, $params, $this);
}

            
renderContent() public method (available since version 2.0.1)

定義於: yii\base\Controller::renderContent()

透過套用版面配置渲染靜態字串。

public string renderContent ( $content )
$content string

要渲染的靜態字串

return string

將給定的靜態字串作為 $content 變數的版型渲染結果。如果版型已停用,則會將字串傳回。

                public function renderContent($content)
{
    $layoutFile = $this->findLayoutFile($this->getView());
    if ($layoutFile !== false) {
        return $this->getView()->renderFile($layoutFile, ['content' => $content], $this);
    }
    return $content;
}

            
renderFile() public method

定義於: yii\base\Controller::renderFile()

渲染視圖檔案。

public string renderFile ( $file, $params = [] )
$file string

要渲染的 view 檔案。這可以是檔案路徑或 路徑別名

$params array

應在 view 中提供的參數(名稱-值對)。

return string

渲染結果。

throws yii\base\InvalidArgumentException

如果 view 檔案不存在。

                public function renderFile($file, $params = [])
{
    return $this->getView()->renderFile($file, $params, $this);
}

            
renderPartial() public method

定義於: yii\base\Controller::renderPartial()

渲染視圖但不套用版面配置。

此方法與 render() 的不同之處在於它不套用任何版型。

public string renderPartial ( $view, $params = [] )
$view string

View 名稱。請參閱 render() 了解如何指定 view 名稱。

$params array

應在 view 中提供的參數(名稱-值對)。

return string

渲染結果。

throws yii\base\InvalidArgumentException

如果 view 檔案不存在。

                public function renderPartial($view, $params = [])
{
    return $this->getView()->render($view, $params, $this);
}

            
run() public method

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

動作的結果。

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

            
runAction() public method

定義於: yii\base\Controller::runAction()

使用指定的動作 ID 和參數在此控制器中執行動作。

如果 action ID 為空,此方法將會使用 $defaultAction

另請參閱 createAction()

public mixed runAction ( $id, $params = [] )
$id string

要執行的 action 的 ID。

$params array

要傳遞給 action 的參數 (名稱-值 對)。

return mixed

動作的結果。

throws yii\base\InvalidRouteException

如果請求的 action ID 無法成功解析為 action 時。

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

            
serializeData() protected method

序列化指定的資料。

預設實作將根據 $serializer 給定的配置建立一個序列化器。然後它使用該序列化器來序列化給定的資料。

protected mixed serializeData ( $data )
$data mixed

要被序列化的資料

return mixed

序列化後的資料。

                protected function serializeData($data)
{
    return Yii::createObject($this->serializer)->serialize($data);
}

            
setView() public method

定義於: yii\base\Controller::setView()

設定此控制器要使用的視圖物件。

public void setView ( $view )
$view yii\base\View|yii\web\View

可用於渲染視圖或視圖檔案的視圖物件。

                public function setView($view)
{
    $this->_view = $view;
}

            
setViewPath() public method (available since version 2.0.7)

定義於: yii\base\Controller::setViewPath()

設定包含視圖檔案的目錄。

public void setViewPath ( $path )
$path string

檢視檔案的根目錄。

throws yii\base\InvalidArgumentException

如果目錄無效

                public function setViewPath($path)
{
    $this->_viewPath = Yii::getAlias($path);
}

            
trigger() public method

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

觸發事件。

此方法表示事件的發生。它會呼叫所有附加到事件的處理器,包括類別層級的處理器。

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

            
verbs() protected method

宣告允許的 HTTP 動詞。

請參考 yii\filters\VerbFilter::$actions 關於如何宣告允許的動詞。

protected array verbs ( )
return array

允許的 HTTP 動詞。

                protected function verbs()
{
    return [];
}