Yii/web中的Controller类,实现参数绑定,启动csrf验证功能,重定向页面功能:

 namespace yii\web;

 use Yii;
 use yii\base\InlineAction;
 use yii\helpers\Url;

 /**
  * Controller is the base class of web controllers.
  *
  * @author Qiang Xue <qiang.xue@gmail.com>
  * @since 2.0
  */
 class Controller extends \yii\base\Controller
 {
     /**
      * @var boolean whether to enable CSRF validation for the actions in this controller.
      * @var boolean 是否启动CSRF验证标记
      * CSRF validation is enabled only when both this property and [[Request::enableCsrfValidation]] are true.
      */
     public $enableCsrfValidation = true;
     /**
      * @var array the parameters bound to the current action.
      * @var array 绑定到当前操作的参数
      */
     public $actionParams = [];

     /**
      * Renders a view in response to an AJAX request.
      * 这个渲染的结果用来作为ajax请求的的响应
      *
      * This method is similar to [[renderPartial()]] except that it will inject into
      * the rendering result with JS/CSS scripts and files which are registered with the view.
      * For this reason, you should use this method instead of [[renderPartial()]] to render
      * a view to respond to an AJAX request.
      * 这个方法和renderPartial类似,但这个返回的结果中会包含css/js以及其它在view中注册的文件。
      *
      * @param string $view the view name. Please refer to [[render()]] on how to specify a view name.
      * @param array $params the parameters (name-value pairs) that should be made available in the view.
      * @return string the rendering result.
      */
     public function renderAjax($view, $params = [])
     {
         return $this->getView()->renderAjax($view, $params, $this);
     }

     /**
      * Binds the parameters to the action.
      * 基类的 action 中绑定参数功能的实现
      * This method is invoked by [[\yii\base\Action]] when it begins to run with the given parameters.
      * This method will check the parameter names that the action requires and return
      * the provided parameters according to the requirement. If there is any missing parameter,
      * an exception will be thrown.
      * 根据action中定义的参数,从$_GET中取对应的值,
      * 如果没有,则抛出异常
      * @param \yii\base\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.
      * @throws BadRequestHttpException if there are missing or invalid parameters.
      */
     public function bindActionParams($action, $params)
     {
         if ($action instanceof InlineAction) {//如果action继承InlineAction
             $method = new \ReflectionMethod($this, $action->actionMethod);//通过反射得到动作action的方法信息
         } else {
             $method = new \ReflectionMethod($action, 'run');//如果action继承Action基类,通过反射得到动作action的方法信息,并实现里面的run方法
         }

         $args = [];
         $missing = [];
         $actionParams = [];
         foreach ($method->getParameters() as $param) {
              //获取在action中定义的参数的名称
             $name = $param->getName();
             if (array_key_exists($name, $params)) {
                 if ($param->isArray()) {//如果参数是数组类型的,如果从传入的参数中取得的数据是数组则返回,否则将得到的参数转换为数组
                     $args[] = $actionParams[$name] = (array) $params[$name];
                 } elseif (!is_array($params[$name])) {//如果不是数组,直接返回传入的参数中对应的结果
                     $args[] = $actionParams[$name] = $params[$name];
                 } else {
                     throw new BadRequestHttpException(Yii::t('yii', 'Invalid data received for parameter "{param}".', [
                         'param' => $name,
                     ]));
                 }
                 unset($params[$name]);
             } elseif ($param->isDefaultValueAvailable()) { //如果默认有默认值取默认值
                 $args[] = $actionParams[$name] = $param->getDefaultValue();
             } else {//action中定义的参数没有在传入的参数中找到,标记的missing中
                 $missing[] = $name;
             }
         }

         if (!empty($missing)) {//action中的参数有缺少,抛出异常
             throw new BadRequestHttpException(Yii::t('yii', 'Missing required parameters: {params}', [
                 'params' => implode(', ', $missing),
             ]));
         }

         $this->actionParams = $actionParams;

         return $args;
     }

     /**
      * @inheritdoc  重写基类的beforeAction
      */
     public function beforeAction($action)
     {
         if (parent::beforeAction($action)) {
             //父类的beforAction方法执行成功后,启动csrf验证功能
             if ($this->enableCsrfValidation && Yii::$app->getErrorHandler()->exception === null && !Yii::$app->getRequest()->validateCsrfToken()) {
                 throw new BadRequestHttpException(Yii::t('yii', 'Unable to verify your data submission.'));
             }
             return true;
         }

         return false;
     }

     /**
      * Redirects the browser to the specified URL.
      * 重定向方法[[Response::redirect()]]的短方法
      * This method is a shortcut to [[Response::redirect()]].
      *
      * You can use it in an action by returning the [[Response]] directly:
      * 下面的例子是重定向到longin
      * ```php
      * // stop executing this action and redirect to login page
      * return $this->redirect(['login']);
      * ```
      *
      * @param string|array $url the URL to be redirected to. This can be in one of the following formats:
      * @param string|array $url 重定向的URL,有下列三种形式
      *
      * - a string representing a URL (e.g. "http://example.com")
      *   一个字符串URL
      * - a string representing a URL alias (e.g. "@example.com")
      *   别名形式的URL
      * - an array in the format of `[$route, ...name-value pairs...]` (e.g. `['site/index', 'ref' => 1]`)
      *   数组,第一个元素为生成路径的参数,后面的元素为链接中传递的参数
      *   [[Url::to()]] will be used to convert the array into a URL.
      *
      * Any relative URL will be converted into an absolute one by prepending it with the host info
      * of the current request.
      * 如果传入的是相对的url,都会根据当前请求的host info 转换为绝对url
      *
      * @param integer $statusCode the HTTP status code. Defaults to 302.
      * See <http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html>
      * for details about HTTP status code
      * @return Response the current response object
      */
     public function redirect($url, $statusCode = 302)
     {
         return Yii::$app->getResponse()->redirect(Url::to($url), $statusCode);
     }

     /**
      * Redirects the browser to the home page.
      * 重定向到首页
      *
      * You can use this method in an action by returning the [[Response]] directly:
      *
      * ```php
      * // stop executing this action and redirect to home page
      * return $this->goHome();
      * ```
      *
      * @return Response the current response object
      */
     public function goHome()
     {
         return Yii::$app->getResponse()->redirect(Yii::$app->getHomeUrl());
     }

     /**
      * Redirects the browser to the last visited page.
      * 返回上一页
      *
      * You can use this method in an action by returning the [[Response]] directly:
      *
      * ```php
      * // stop executing this action and redirect to last visited page
      * return $this->goBack();
      * ```
      *
      * For this function to work you have to [[User::setReturnUrl()|set the return URL]] in appropriate places before.
      *
      * @param string|array $defaultUrl the default return URL in case it was not set previously.
      * If this is null and the return URL was not set previously, [[Application::homeUrl]] will be redirected to.
      * Please refer to [[User::setReturnUrl()]] on accepted format of the URL.
      * @return Response the current response object
      * @see User::getReturnUrl()
      */
     public function goBack($defaultUrl = null)
     {
         return Yii::$app->getResponse()->redirect(Yii::$app->getUser()->getReturnUrl($defaultUrl));
     }

     /**
      * Refreshes the current page.
      * 刷新页面
      * This method is a shortcut to [[Response::refresh()]].
      *
      * You can use it in an action by returning the [[Response]] directly:
      *
      * ```php
      * // stop executing this action and refresh the current page
      * return $this->refresh();
      * ```
      *
      * @param string $anchor the anchor that should be appended to the redirection URL.
      * Defaults to empty. Make sure the anchor starts with '#' if you want to specify it.
      * @return Response the response object itself
      */
     public function refresh($anchor = '')
     {
         return Yii::$app->getResponse()->redirect(Yii::$app->getRequest()->getUrl() . $anchor);
     }
 }

Yii源码阅读笔记(二十八)的更多相关文章

  1. Yii源码阅读笔记(十八)

    View中的查找视图文件方法和渲染文件方法 /** * Finds the view file based on the given view name. * 通过view文件名查找view文件 * ...

  2. Yii源码阅读笔记(十二)

    Action类,控制器中方法的基类: namespace yii\base; use Yii; /** * Action is the base class for all controller ac ...

  3. Yii源码阅读笔记(十五)

    Model类,集中整个应用的数据和业务逻辑——验证 /** * Returns the attribute labels. * 返回属性的标签 * * Attribute labels are mai ...

  4. Yii源码阅读笔记(十六)

    Model类,集中整个应用的数据和业务逻辑—— /** * Generates a user friendly attribute label based on the give attribute ...

  5. Yii源码阅读笔记(十四)

    Model类,集中整个应用的数据和业务逻辑——场景.属性和标签: /** * Returns a list of scenarios and the corresponding active attr ...

  6. Yii源码阅读笔记(十)

    控制器类,所有控制器的基类,用于调用模型和布局,输出到视图 namespace yii\base; use Yii; /** * Controller is the base class for cl ...

  7. Yii源码阅读笔记(十九)

    View中渲染view视图文件的前置和后置方法,以及渲染动态内容的方法: /** * @return string|boolean the view file currently being rend ...

  8. Yii源码阅读笔记(一)

    今天开始阅读yii2的源码,想深入了解一下yii框架的工作原理,同时学习一下优秀的编码规范和风格.在此记录一下阅读中的小心得. 每个框架都有一个入口文件,首先从入口文件开始,yii2的入口文件位于we ...

  9. werkzeug源码阅读笔记(二) 下

    wsgi.py----第二部分 pop_path_info()函数 先测试一下这个函数的作用: >>> from werkzeug.wsgi import pop_path_info ...

  10. werkzeug源码阅读笔记(二) 上

    因为第一部分是关于初始化的部分的,我就没有发布出来~ wsgi.py----第一部分 在分析这个模块之前, 需要了解一下WSGI, 大致了解了之后再继续~ get_current_url()函数 很明 ...

随机推荐

  1. 记一次Runtime的巧用

    背景 我们的视频直播是用的大华乐橙的解决方案,而他们近期出来个新的SDK,并且对老版SDK不兼容,而这周,终于把大华乐橙的新版SDK切换了,和这一周做的新的东西,一起提交审核了,并且今天也通过审核了. ...

  2. three.js入门3

    为什么要用three.js Three.js为我们封装了底层的WebGl接口,使我们在无需掌握繁冗的图形学知识的基础下可以轻松的创建三维场景.相比较使用底层的WebGL我们可以使用更少的代码,大大的降 ...

  3. Codeforces 675E Trains and Statistic(DP + 贪心 + 线段树)

    题目大概说有n(<=10W)个车站,每个车站i卖到车站i+1...a[i]的票,p[i][j]表示从车站i到车站j所需买的最少车票数,求所有的p[i][j](i<j)的和. 好难,不会写. ...

  4. 使用oracle11g_instant_client来解决在不安装oracle客户端的情况下连接服务端

    一.下载instantclient_11_2,可去oracle官网进行下载. 二.解压缩下载的instantclient_11_2,将instantclient_11_2目录拖放到C:\Program ...

  5. iOS学习28之UITabBarController

    1. 标签视图控制器 -- UITabBarController 视图(UIView) ---> 图层 ---> 子视图 视图控制器(UIViewController) ---> 管 ...

  6. BZOJ 1053 & 反素数

    题意: 反素数,膜一篇GOD's Blog...http://blog.csdn.net/ACdreamers/article/details/25049767 此文一出,无与争锋... CODE: ...

  7. hdu 1312 Red and Black

    Problem Description There is a rectangular room, covered with square tiles. Each tile is colored eit ...

  8. java画图程序_图片用字母画出来_源码发布_版本二

    在上一个版本:java画图程序_图片用字母画出来_源码发布 基础上,增加了图片同比例缩放,使得大像素图片可以很好地显示画在Notepad++中. 项目结构: 运行效果1: 原图:http://imag ...

  9. Photoshop教您快速的制作标准一寸证件照教程

    Photoshop教您快速的制作标准一寸证件照教程 对急需证件照的朋友,只要有一部相机,有电脑安装了PS软件,就可很快自己完成一寸照片的制作. 首先将相机卡里的照片存放在电脑硬盘里: 打开PS图片处理 ...

  10. Redis集群的配置

    [转]Redis集群的配置 一:memcache 和 Redis 对比总结 [memecache 特点] 1:速度最快(没有自测,但网上有详细的测试用例) 2:支持水平扩展,可以任意添加节点 [red ...