1 關注者

類別 yii\web\Controller

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

Controller 是 Web 控制器的基底類別。

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

公開屬性

隱藏繼承的屬性

屬性 類型 描述 定義於
$action yii\base\Action|null 目前正在執行的動作。 yii\base\Controller
$actionParams 陣列 繫結到目前動作的參數。 yii\web\Controller
$behaviors yii\base\Behavior[] 附加到此組件的行為列表。 yii\base\Component
$defaultAction 字串 當請求中未指定動作 ID 時,使用的動作 ID。 yii\base\Controller
$enableCsrfValidation 布林值 是否為此控制器中的動作啟用 CSRF 驗證。 yii\web\Controller
$id 字串 此控制器的 ID。 yii\base\Controller
$layout 字串|null|false 將應用於此控制器視圖的版面配置名稱。 yii\base\Controller
$module yii\base\Module 此控制器所屬的模組。 yii\base\Controller
$modules yii\base\Module[] 此控制器所在的所有祖先模組。 yii\base\Controller
$request yii\base\Request|陣列|字串 請求。 yii\base\Controller
$response yii\base\Response|陣列|字串 回應。 yii\base\Controller
$route 字串 目前請求的路由(模組 ID、控制器 ID 和動作 ID)。 yii\base\Controller
$uniqueId 字串 以模組 ID(如果有的話)為前綴的控制器 ID。 yii\base\Controller
$view yii\base\View|yii\web\View 可用於渲染視圖或視圖檔案的視圖物件。 yii\base\Controller
$viewPath 字串 包含此控制器視圖檔案的目錄。 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\base\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\base\Component
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

Protected Methods

隱藏繼承的方法

方法 描述 定義於
bindInjectedParams() 根據動作方法簽名中的類型和名稱填充參數。 yii\base\Controller

Events

Hide inherited events

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

Property Details

隱藏繼承的屬性

$actionParams public property

繫結到目前動作的參數。

public array $actionParams = []
$enableCsrfValidation public property

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

Method Details

隱藏繼承的方法

__call() public method

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

呼叫非類別方法的具名方法。

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

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

public mixed __call ( $name, $params )
$name 字串

方法名稱

$params 陣列

方法參數

return mixed

方法的返回值

throws yii\base\UnknownMethodException

當呼叫未知方法時

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

            
__clone() public method

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

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

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

public void __clone ( )

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

            
__construct() public method
public void __construct ( $id, $module, $config = [] )
$id 字串

此控制器的 ID。

$module yii\base\Module

此控制器所屬的模組。

$config 陣列

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

                public function __construct($id, $module, $config = [])
{
    $this->id = $id;
    $this->module = $module;
    parent::__construct($config);
}

            
__get() public method

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

傳回組件屬性的值。

此方法將按以下順序檢查並採取相應措施

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

不要直接呼叫此方法,因為它是一個 PHP 魔術方法,當執行 $value = $component->property; 時會被隱式呼叫。

另請參閱 __set()

public mixed __get ( $name )
$name 字串

屬性名稱

return mixed

屬性值或行為的屬性值

throws yii\base\UnknownPropertyException

如果未定義屬性

throws yii\base\InvalidCallException

如果屬性是唯寫的。

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

            
__isset() public method

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

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

此方法將按以下順序檢查並採取相應措施

  • setter 定義的屬性:返回屬性是否已設定
  • 行為的屬性:返回屬性是否已設定
  • 對於不存在的屬性返回 false

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

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

public boolean __isset ( $name )
$name 字串

屬性名稱或事件名稱

return 布林值

已命名的屬性是否已設定

                public function __isset($name)
{
    $getter = 'get' . $name;
    if (method_exists($this, $getter)) {
        return $this->$getter() !== null;
    }
    // behavior property
    $this->ensureBehaviors();
    foreach ($this->_behaviors as $behavior) {
        if ($behavior->canGetProperty($name)) {
            return $behavior->$name !== null;
        }
    }
    return false;
}

            
__set() public method

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

設定組件屬性的值。

此方法將按以下順序檢查並採取相應措施

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

不要直接呼叫此方法,因為它是一個 PHP 魔術方法,當執行 $component->property = $value; 時會被隱式呼叫。

另請參閱 __get()

public void __set ( $name, $value )
$name 字串

屬性名稱或事件名稱

$value mixed

屬性值

throws yii\base\UnknownPropertyException

如果未定義屬性

throws yii\base\InvalidCallException

如果屬性是唯讀的。

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

            
__unset() public method

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

將組件屬性設定為 null。

此方法將按以下順序檢查並採取相應措施

  • setter 定義的屬性:將屬性值設定為 null
  • 行為的屬性:將屬性值設定為 null

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

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

public void __unset ( $name )
$name 字串

屬性名稱

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

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

Defined in: yii\base\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 mixed

動作返回值。

return mixed

已處理的動作結果。

                public function afterAction($action, $result)
{
    $event = new ActionEvent($action);
    $event->result = $result;
    $this->trigger(self::EVENT_AFTER_ACTION, $event);
    return $event->result;
}

            
asJson() public method (available since version 2.0.11)

以 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() public method (available since version 2.0.11)

以 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() public method

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

將行為附加到此組件。

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

另請參閱 detachBehavior()

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

行為的名稱。

$behavior string|array|yii\base\Behavior

行為配置。可以是以下之一:

return yii\base\Behavior

行為物件

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

            
attachBehaviors() public method

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

將行為列表附加到組件。

每個行為都由其名稱索引,並且應該是一個 yii\base\Behavior 物件、一個指定行為類別的字串,或用於創建行為的配置陣列。

另請參閱 attachBehavior()

public void attachBehaviors ( $behaviors )
$behaviors 陣列

要附加到組件的行為列表

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

            
beforeAction() public method

此方法在動作執行前立即調用。

此方法將觸發 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 布林值

動作是否應繼續運行。

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

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

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

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

此方法的返回值應為行為物件或按行為名稱索引的配置陣列。行為配置可以是指定行為類別的字串或以下結構的陣列:

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

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

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

public array behaviors ( )
return 陣列

行為配置。

                public function behaviors()
{
    return [];
}

            
bindActionParams() public method

將參數繫結到動作。

yii\base\Action 開始使用給定的參數運行時,將調用此方法。此方法將檢查動作需要的參數名稱,並根據需求返回提供的參數。如果缺少任何參數,將拋出異常。

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

要與參數綁定的動作

$params 陣列

要綁定到動作的參數

return 陣列

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

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() protected method (available since version 2.0.36)

Defined in: yii\base\Controller::bindInjectedParams()

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

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

動作參數的反射類型。

$name 字串

參數的名稱。

$args 陣列

動作的參數陣列,此函數可能會將項目附加到其中。

$requestedParams 陣列

帶有請求參數的陣列,此函數可能會將特定鍵寫入其中。

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

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

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

如果滿足以下條件,則可以讀取屬性:

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

另請參閱 canSetProperty()

public boolean canGetProperty ( $name, $checkVars true, $checkBehaviors true )
$name 字串

屬性名稱

$checkVars 布林值

是否將成員變數視為屬性

$checkBehaviors 布林值

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

return 布林值

屬性是否可讀取

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

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

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

如果屬性符合以下條件,則可以寫入:

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

另請參閱 canGetProperty()

public boolean canSetProperty ( $name, $checkVars true, $checkBehaviors true )
$name 字串

屬性名稱

$checkVars 布林值

是否將成員變數視為屬性

$checkBehaviors 布林值

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

return 布林值

屬性是否可寫入

                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() public static method
自 2.0.14 版本起已棄用。在 PHP >=5.5 版本中,請改用 ::class

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

傳回此類別的完整名稱。

public static string className ( )
return 字串

此類別的完整限定名稱。

                public static function className()
{
    return get_called_class();
}

            
createAction() public method

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

根據給定的動作 ID 建立一個動作。

此方法首先檢查動作 ID 是否已在 actions() 中宣告。如果是,它將使用那裡宣告的配置來建立動作物件。如果不是,它將尋找控制器方法,其名稱格式為 actionXyz,其中 xyz 是動作 ID。如果找到,將建立並傳回代表該方法的 yii\base\InlineAction

public yii\base\Action|null createAction ( $id )
$id 字串

動作 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()

從組件卸載一個行為。

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

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

行為的名稱。

return yii\base\Behavior|null

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

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

            
detachBehaviors() 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

要呈現版面配置檔案的視圖物件。

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 字串

行為名稱

return yii\base\Behavior|null

行為物件,或如果行為不存在則為 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[]

附加到此元件的行為列表

                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 字串

目前請求的路由(模組 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 字串

以模組 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" 應用程式元件。

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 字串

包含此控制器視圖檔案的目錄。

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

            
goBack() public method

將瀏覽器重定向到上次訪問的頁面。

您可以在動作中使用此方法,方法是直接傳回 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\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 字串

事件名稱

return 布林值

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

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

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

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

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

屬性名稱

$checkBehaviors 布林值

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

return 布林值

方法是否已定義

                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 時);
  • 附加的行為具有給定名稱的屬性(當 $checkBehaviors 為 true 時)。

另請參閱

public boolean hasProperty ( $name, $checkVars true, $checkBehaviors true )
$name 字串

屬性名稱

$checkVars 布林值

是否將成員變數視為屬性

$checkBehaviors 布林值

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

return 布林值

屬性是否已定義

                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 字串

事件名稱

$handler callable|null

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

return 布林值

如果找到並分離處理常式

                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)

其中 $eventyii\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 字串

事件名稱

$handler callable

事件處理常式

$data mixed

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

$append 布林值

是否將新的事件處理常式附加到現有處理常式列表的末尾。如果為 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

將瀏覽器重定向到指定的 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 integer

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\Response::refresh() 的快捷方式。

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

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

應附加到重新導向 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()

渲染視圖並應用佈局(如果可用)。

要呈現的視圖可以使用以下格式之一指定

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

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

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

如果 layout 名稱不包含檔案副檔名,則會使用預設的 .php

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

視圖名稱。

$params 陣列

應該在視圖中可用的參數(名稱-值對)。這些參數在 layout 中將不可用。

return 字串

渲染結果。

throws yii\base\InvalidArgumentException

如果視圖檔案或 layout 檔案不存在。

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

            
renderAjax() public 方法

響應 AJAX 請求渲染視圖。

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

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

視圖名稱。請參考 render() 關於如何指定視圖名稱的說明。

$params 陣列

應該在視圖中可用的參數(名稱-值對)。

return 字串

渲染結果。

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

            
renderContent() public 方法 (自版本 2.0.1 起可用)

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

通過應用佈局渲染靜態字串。

public string renderContent ( $content )
$content 字串

要渲染的靜態字串

return 字串

使用給定的靜態字串作為 $content 變數的 layout 渲染結果。如果 layout 被禁用,則會返回該字串。

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

            
renderFile() public 方法

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

渲染視圖檔案。

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

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

$params 陣列

應該在視圖中可用的參數(名稱-值對)。

return 字串

渲染結果。

throws yii\base\InvalidArgumentException

如果視圖檔案不存在。

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

            
renderPartial() public 方法

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

渲染視圖但不應用佈局。

此方法與 render() 的不同之處在於它不應用任何 layout。

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

視圖名稱。請參考 render() 關於如何指定視圖名稱的說明。

$params 陣列

應該在視圖中可用的參數(名稱-值對)。

return 字串

渲染結果。

throws yii\base\InvalidArgumentException

如果視圖檔案不存在。

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

            
run() public 方法

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

運行以路徑形式指定的請求。

路由可以是此控制器中 action 的 ID,或由模組 ID、控制器 ID 和 action ID 組成的完整路由。如果路由以斜線 '/' 開頭,則路由的解析將從應用程式開始;否則,它將從此控制器的父模組開始。

另請參閱 runAction()

public mixed run ( $route, $params = [] )
$route 字串

要處理的路由,例如 'view'、'comment/view'、'/admin/comment/view'。

$params 陣列

要傳遞給 action 的參數。

return mixed

action 的結果。

                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 方法

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

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

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

另請參閱 createAction()

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

要執行的 action 的 ID。

$params 陣列

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

return mixed

action 的結果。

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

            
setView() public 方法

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

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

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

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

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

            
setViewPath() public 方法 (自版本 2.0.7 起可用)

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

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

public void setViewPath ( $path )
$path 字串

視圖檔案的根目錄。

throws yii\base\InvalidArgumentException

如果目錄無效

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

            
trigger() public 方法

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

觸發一個事件。

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

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

事件名稱

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