热门标签 | HotTags
当前位置:  开发笔记 > 编程语言 > 正文

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


推荐阅读
  • 本文介绍了《中秋夜作》的翻译及原文赏析,以及诗人当代钱钟书的背景和特点。通过对诗歌的解读,揭示了其中蕴含的情感和意境。 ... [详细]
  • 本文详细介绍了SQL日志收缩的方法,包括截断日志和删除不需要的旧日志记录。通过备份日志和使用DBCC SHRINKFILE命令可以实现日志的收缩。同时,还介绍了截断日志的原理和注意事项,包括不能截断事务日志的活动部分和MinLSN的确定方法。通过本文的方法,可以有效减小逻辑日志的大小,提高数据库的性能。 ... [详细]
  • 搭建Windows Server 2012 R2 IIS8.5+PHP(FastCGI)+MySQL环境的详细步骤
    本文详细介绍了搭建Windows Server 2012 R2 IIS8.5+PHP(FastCGI)+MySQL环境的步骤,包括环境说明、相关软件下载的地址以及所需的插件下载地址。 ... [详细]
  • PHP图片截取方法及应用实例
    本文介绍了使用PHP动态切割JPEG图片的方法,并提供了应用实例,包括截取视频图、提取文章内容中的图片地址、裁切图片等问题。详细介绍了相关的PHP函数和参数的使用,以及图片切割的具体步骤。同时,还提供了一些注意事项和优化建议。通过本文的学习,读者可以掌握PHP图片截取的技巧,实现自己的需求。 ... [详细]
  • 关羽败走麦城时路过马超封地 马超为何没有出手救人
    对当年关羽败走麦城,恰好路过马超的封地,为啥马超不救他?很感兴趣的小伙伴们,趣历史小编带来详细的文章供大家参考。说到英雄好汉,便要提到一本名著了,没错,那就是《三国演义》。书中虽 ... [详细]
  • 本文分享了一个关于在C#中使用异步代码的问题,作者在控制台中运行时代码正常工作,但在Windows窗体中却无法正常工作。作者尝试搜索局域网上的主机,但在窗体中计数器没有减少。文章提供了相关的代码和解决思路。 ... [详细]
  • 本文介绍了使用Java实现大数乘法的分治算法,包括输入数据的处理、普通大数乘法的结果和Karatsuba大数乘法的结果。通过改变long类型可以适应不同范围的大数乘法计算。 ... [详细]
  • PHP设置MySQL字符集的方法及使用mysqli_set_charset函数
    本文介绍了PHP设置MySQL字符集的方法,详细介绍了使用mysqli_set_charset函数来规定与数据库服务器进行数据传送时要使用的字符集。通过示例代码演示了如何设置默认客户端字符集。 ... [详细]
  • Java序列化对象传给PHP的方法及原理解析
    本文介绍了Java序列化对象传给PHP的方法及原理,包括Java对象传递的方式、序列化的方式、PHP中的序列化用法介绍、Java是否能反序列化PHP的数据、Java序列化的原理以及解决Java序列化中的问题。同时还解释了序列化的概念和作用,以及代码执行序列化所需要的权限。最后指出,序列化会将对象实例的所有字段都进行序列化,使得数据能够被表示为实例的序列化数据,但只有能够解释该格式的代码才能够确定数据的内容。 ... [详细]
  • 橱窗设计的表现手法及其应用
    本文介绍了橱窗设计的表现手法,包括直接展示、寓意与联想、夸张与幽默等。通过对商品的折、拉、叠、挂、堆等陈列技巧,橱窗设计能够充分展现商品的形态、质地、色彩、样式等特性。同时,寓意与联想可以通过象形形式或抽象几何道具来唤起消费者的联想与共鸣,创造出强烈的时代气息和视觉空间。合理的夸张和贴切的幽默能够明显夸大商品的美的因素,给人以新颖奇特的心理感受,引起人们的笑声和思考。通过这些表现手法,橱窗设计能够有效地传达商品的个性内涵,吸引消费者的注意力。 ... [详细]
  • HDU 2372 El Dorado(DP)的最长上升子序列长度求解方法
    本文介绍了解决HDU 2372 El Dorado问题的一种动态规划方法,通过循环k的方式求解最长上升子序列的长度。具体实现过程包括初始化dp数组、读取数列、计算最长上升子序列长度等步骤。 ... [详细]
  • faceu激萌变老特效的使用方法详解
    本文介绍了faceu激萌变老特效的使用方法,包括打开faceu激萌app、点击贴纸、选择热门贴纸中的变老特效,然后对准人脸进行拍摄,即可给照片添加变老特效。操作简单,适合新用户使用。 ... [详细]
  • Android中高级面试必知必会,积累总结
    本文介绍了Android中高级面试的必知必会内容,并总结了相关经验。文章指出,如今的Android市场对开发人员的要求更高,需要更专业的人才。同时,文章还给出了针对Android岗位的职责和要求,并提供了简历突出的建议。 ... [详细]
  • 大连微软技术社区举办《.net core始于足下》活动,获得微软赛百味和易迪斯的赞助
    九月十五日,大连微软技术社区举办了《.net core始于足下》活动,共有51人报名参加,实际到场人数为43人,还有一位专程从北京赶来的同学。活动得到了微软赛百味和易迪斯的赞助,场地也由易迪斯提供。活动中大家积极交流,取得了非常成功的效果。 ... [详细]
  • 给定一个二叉树,要求随机选择树上的一个节点。解法:遍历树的过程中,随机选择一个节点即可。具体做法参看:从输入 ... [详细]
author-avatar
快乐宝宝的哭泣_826
这个家伙很懒,什么也没留下!
PHP1.CN | 中国最专业的PHP中文社区 | DevBox开发工具箱 | json解析格式化 |PHP资讯 | PHP教程 | 数据库技术 | 服务器技术 | 前端开发技术 | PHP框架 | 开发工具 | 在线工具
Copyright © 1998 - 2020 PHP1.CN. All Rights Reserved | 京公网安备 11010802041100号 | 京ICP备19059560号-4 | PHP1.CN 第一PHP社区 版权所有