程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
 程式師世界 >> 編程語言 >> 網頁編程 >> PHP編程 >> 關於PHP編程 >> yii2源碼學習筆記(十二),yii2源碼學習筆記

yii2源碼學習筆記(十二),yii2源碼學習筆記

編輯:關於PHP編程

yii2源碼學習筆記(十二),yii2源碼學習筆記


繼續了解controller基類。

    /**
     * Runs a request specified in terms of a route.在路徑中指定的請求。
     * The route can be either an ID of an action within this controller or a complete route consisting
     * of module IDs, controller ID and action ID. If the route starts with a slash '/', the parsing of
     * the route will start from the application; otherwise, it will start from the parent module of this controller.
     * 該路徑可以是控制器內的一個動作的標識,或由模塊標識、控制器標識和動作標識組成的一個完整路徑。
     * 如果該路徑從一個“/”開始,該路徑的解析將從應用程序開始;否則,它將從該控制器的父模塊開始。
     * @param string $route the route to be handled, e.g., 'view', 'comment/view', '/admin/comment/view'.
     * @param array $params the parameters to be passed to the action.
     * @return mixed the result of the action.
     * @see runAction()
     */
    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);
        } else {
            return Yii::$app->runAction(ltrim($route, '/'), $params);
        }
    }

    /**
     * Binds the parameters to the action.將參數綁定到動作標識。
     * This method is invoked by [[Action]] when it begins to run with the given parameters.
     * 運行給定的參數時,該方法被調用。
     * @param Action $action the action to be bound with parameters.參數約束的操作。
     * @param array $params the parameters to be bound to the action.要約束的參數。
     * @return array the valid parameters that the action can run with.可以運行的有效參數。
     */
    public function bindActionParams($action, $params)
    {
        return [];
    }

    /**
     * Creates an action based on the given action ID. 根據給定的操作標識創建一個action。
     * The method first checks if the action ID has been declared in [[actions()]]. If so,
     * it will use the configuration declared there to create the action object.
     * If not, it will look for a controller method whose name is in the format of `actionXyz`
     * where `Xyz` stands for the action ID. If found, an [[InlineAction]] representing that
     * method will be created and returned.
     * 該方法首先檢查動作標識是否在 [[actions()]]設置,如果是將使用配置聲明來創建操作對象。
     * 如果不是,它會尋找控制器方法`Xyz` 的 `actionXyz`作為動作標識,調用[[InlineAction]]方法創建對象
     * @param string $id the action ID. 
     * @return Action the newly created action instance. Null if the ID doesn't resolve into any action.
     */
    public function createAction($id)
    {
        if ($id === '') {
             // 如果action的id為空,就是用默認的action
            $id = $this->defaultAction;
        }

        $actionMap = $this->actions();// 獲取actions方法中的定義的actionMap
        if (isset($actionMap[$id])) {
             // 如果操作標識在actionMap中,就去創建這個action
            return Yii::createObject($actionMap[$id], [$id, $this]);
        } elseif (preg_match('/^[a-z0-9\\-_]+$/', $id) && strpos($id, '--') === false && trim($id, '-') === $id) {
             // 如果id符合命名規范,而且兩邊不存在-
            // 用於拼接controller類名類似的方法拼接action方法的名稱
            $methodName = 'action' . str_replace(' ', '', ucwords(implode(' ', explode('-', $id))));
            if (method_exists($this, $methodName)) {
                // 如果方法存在,就實例化
                $method = new \ReflectionMethod($this, $methodName);
                if ($method->isPublic() && $method->getName() === $methodName) {
                    // 如果方法是public的,就new一個InlineAction返回
                    return new InlineAction($id, $this, $methodName);
                }
            }
        }

        return null;
    }

    /**
     * This method is invoked right before an action is executed.
     * 在執行操作之前調用此方法。
     * The method will trigger the [[EVENT_BEFORE_ACTION]] event. The return value of the method
     * will determine whether the action should continue to run.
     * 方法將觸發 [[EVENT_BEFORE_ACTION]] 事件,返回值確定該操作是否執行
     * If you override this method, your code should look like the following:
     *
     * ```php
     * public function beforeAction($action)
     * {
     *     if (parent::beforeAction($action)) {
     *         // your custom code here
     *         return true;  // or false if needed
     *     } else {
     *         return false;
     *     }
     * }
     * ```
     *
     * @param Action $action the action to be executed. 執行的操作
     * @return boolean whether the action should continue to run.確定操作是否應該繼續運行。
     */
    public function beforeAction($action)
    {
        $event = new ActionEvent($action);
        $this->trigger(self::EVENT_BEFORE_ACTION, $event);
        return $event->isValid;
    }

    /**
     * This method is invoked right after an action is executed.
     * 在執行操作之後調用此方法。
     * The method will trigger the [[EVENT_AFTER_ACTION]] event. The return value of the method
     * will be used as the action return value.
     *
     * If you override this method, your code should look like the following:
     *
     * ```php
     * public function afterAction($action, $result)
     * {
     *     $result = parent::afterAction($action, $result);
     *     // your custom code here
     *     return $result;
     * }
     * ```
     *
     * @param Action $action the action just executed. 剛剛執行的操作。
     * @param mixed $result the action return result. 操作返回值
     * @return mixed the processed action result. 處理結果。
     */
    public function afterAction($action, $result)
    {
        $event = new ActionEvent($action);
        $event->result = $result;
        $this->trigger(self::EVENT_AFTER_ACTION, $event);
        return $event->result;
    }

    /**
     * Returns all ancestor modules of this controller. 獲取當前控制器所有的父模塊
     * The first module in the array is the outermost one (i.e., the application instance),
     * while the last is the innermost one.
     * 數組中的第一個模塊是最外層的一個,最後一個模塊是最內層的。
     * @return Module[] all ancestor modules that this controller is located within.當前控制器所有的父模塊
     */
    public function getModules()
    {
        // 當前controller的module組成的數組
        $modules = [$this->module];
        $module = $this->module;
        while ($module->module !== null) {
             // 將外面的module插入到modules數組的開頭
            array_unshift($modules, $module->module);
            $module = $module->module;
        }
        return $modules;
    }

    /**
     * @return string the controller ID that is prefixed with the module ID (if any).
     * 返回控制器id
     */
    public function getUniqueId()
    {
        //如果當前所屬模塊為application,則就為當前id,否則要面要加上模塊id
        return $this->module instanceof Application ? $this->id : $this->module->getUniqueId() . '/' . $this->id;
    }

    /**
     * Returns the route of the current request.    獲取默認請求的路由信息
     * @return string the route (module ID, controller ID and action ID) of the current request. 
     * 當前請求的路由(模塊標識、控制器標識和操作標識)
     */
    public function getRoute()
    {
        return $this->action !== null ? $this->action->getUniqueId() : $this->getUniqueId();
    }

    /**
     * Renders a view and applies layout if available.
     * 如果有布局渲染視圖文件和布局文件
     * The view to be rendered can be specified in one of the following formats:
     *
     * - path alias (e.g. "@app/views/site/index");
     * - absolute path within application (e.g. "//site/index"): the view name starts with double slashes.
     *   The actual view file will be looked for under the [[Application::viewPath|view path]] of the application.
     * - absolute path within module (e.g. "/site/index"): the view name starts with a single slash.
     *   The actual view file will be looked for under the [[Module::viewPath|view path]] of [[module]].
     * - relative path (e.g. "index"): the actual view file will be looked for under [[viewPath]].
     *
     * To determine which layout should be applied, the following two steps are conducted:
     * 確定應用布局文件類型的步驟:
     * 1. In the first step, it determines the layout name and the context module:
     * 首先確定布局文件名和背景模塊
     * - If [[layout]] is specified as a string, use it as the layout name and [[module]] as the context module;
     * - If [[layout]] is null, search through all ancestor modules of this controller and find the first
     *   module whose [[Module::layout|layout]] is not null. The layout and the corresponding module
     *   are used as the layout name and the context module, respectively. If such a module is not found
     *   or the corresponding layout is not a string, it will return false, meaning no applicable layout.
     *   如果布局文件是字符串,也就是設置布局文件,則直接調用。 如果沒有設置布局文件,則查找所有的父模塊的布局文件。
     * 2. In the second step, it determines the actual layout file according to the previously found layout name
     *    and context module. The layout name can be:
     *    應用下的布局文件,以“/”開頭,這個會從應用程序的布局文件目錄下面查找布局文件
     * - a path alias (e.g. "@app/views/layouts/main");
     * - an absolute path (e.g. "/main"): the layout name starts with a slash. The actual layout file will be
     *   looked for under the [[Application::layoutPath|layout path]] of the application;
     * - a relative path (e.g. "main"): the actual layout file will be looked for under the
     *   [[Module::layoutPath|layout path]] of the context module.
     *
     * If the layout name does not contain a file extension, it will use the default one `.php`.
     * 如果布局文件沒有擴展名,則默認為.php
     * @param string $view the view name.
     * @param array $params the parameters (name-value pairs) that should be made available in the view.
     * These parameters will not be available in the layout.
     * @return string the rendering result.
     * @throws InvalidParamException if the view file or the layout file does not exist.
     */
    public function render($view, $params = [])
    {
        //由view對象渲染視圖文件
        $content = $this->getView()->render($view, $params, $this);
        return $this->renderContent($content);//渲染布局文件
    }

    /**
     * Renders a static string by applying a layout.    配合render方法渲染布局文件
     * @param string $content the static string being rendered  被渲染的靜態字符串
     * @return string the rendering result of the layout with the given static string as the `$content` variable.
     * If the layout is disabled, the string will be returned back.
     * 以給定的靜態字符串作為“$content”變量布局的渲染結果。如果布局被禁用,將返回該字符串。
     * @since 2.0.1
     */
    public function renderContent($content)
    {
        $layoutFile = $this->findLayoutFile($this->getView()); //查找布局文件
        if ($layoutFile !== false) {//由view對象渲染布局文件,並把上視圖結果作為content變量傳遞到布局中,
            return $this->getView()->renderFile($layoutFile, ['content' => $content], $this);
        } else {
            return $content;
        }
    }

    /**
     * Renders a view without applying layout.渲染視圖文件不應用布局
     * This method differs from [[render()]] in that it does not apply any layout.
     * 這種方法不同於[[render()]],它不使用任何布局。
     * @param string $view the view name. Please refer to [[render()]] on how to specify a view name.
     * 視圖名稱。根據[[render()]]指定一個視圖名稱。
     * @param array $params the parameters (name-value pairs) that should be made available in the view.
     * 在視圖中提供的參數(name-value pairs)
     * @return string the rendering result.渲染結果。
     * @throws InvalidParamException if the view file does not exist.如果視圖文件不存在,拋出異常
     */
    public function renderPartial($view, $params = [])
    {
        return $this->getView()->render($view, $params, $this);
    }

    /**
     * Renders a view file. 渲染一個文件
     * @param string $file the view file to be rendered. This can be either a file path or a path alias.
     * 要呈現的視圖文件。可以是一個文件路徑或路徑別名。
     * @param array $params the parameters (name-value pairs) that should be made available in the view.
     * 在視圖中提供的參數(name-value pairs)
     * @return string the rendering result.渲染結果
     * @throws InvalidParamException if the view file does not exist.如果視圖文件不存在,拋出異常
     */
    public function renderFile($file, $params = [])
    {
        return $this->getView()->renderFile($file, $params, $this);
    }

    /**
     * Returns the view object that can be used to render views or view files.
     * 返回渲染視圖或視圖文件的view對象。
     * The [[render()]], [[renderPartial()]] and [[renderFile()]] methods will use
     * this view object to implement the actual view rendering.
     * [[render()]], [[renderPartial()]] and [[renderFile()]] 方法將使用視圖對象實現視圖顯示。
     * If not set, it will default to the "view" application component.如果未設置,則默認為“view”應用程序組件。
     * @return View|\yii\web\View the view object that can be used to render views or view files.
     * 渲染視圖或視圖文件的view對象。
     */
    public function getView()
    {
        if ($this->_view === null) {
            $this->_view = Yii::$app->getView();
        }
        return $this->_view;
    }

    /**
     * Sets the view object to be used by this controller.
     * @param View|\yii\web\View $view the view object that can be used to render views or view files.
     */
    public function setView($view)
    {
        $this->_view = $view;
    }

    /**
     * Returns the directory containing view files for this controller.返回該控制器包含視圖文件的目錄。
     * The default implementation returns the directory named as controller [[id]] under the [[module]]'s
     * [[viewPath]] directory.默認返回目錄命名為控制器[[id]] 下的 [[module]]的[[viewPath]]目錄。
     * @return string the directory containing the view files for this controller.
     * 包含此控制器的視圖文件的目錄。
     */
    public function getViewPath()
    {
        return $this->module->getViewPath() . DIRECTORY_SEPARATOR . $this->id;
    }

    /**
     * Finds the applicable layout file.查找適用的布局文件。
     * @param View $view the view object to render the layout file.呈現布局文件視圖對象。
     * @return string|boolean the layout file path, or false if layout is not needed.
     * Please refer to [[render()]] on how to specify this parameter.
     * 布局文件路徑,或者不需要布局。參閱[[render()]]如何指定此參數。
     * @throws InvalidParamException if an invalid path alias is used to specify the layout.
     * 如果使用了無效的路徑別名指定布局。拋出異常
     */
    public function findLayoutFile($view)
    {
        $module = $this->module;
        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 (!isset($layout)) {
            return false;//如果沒有設置布局文件,返回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';//如果文件不存在,並且,默認的文件擴展名也不是php,則加上.php作為擴展名。
        }

        return $path;
    }

 

  1. 上一頁:
  2. 下一頁:
Copyright © 程式師世界 All Rights Reserved