您的位置:首页 > 博客中心 > 互联网 >

Yii源码阅读笔记(二十八)

时间:2022-04-29 04:15

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

  1 namespace yii\web;
  2 
  3 use Yii;
  4 use yii\base\InlineAction;
  5 use yii\helpers\Url;
  6 
  7 /**
  8  * Controller is the base class of web controllers.
  9  *
 10  * @author Qiang Xue 
 11  * @since 2.0
 12  */
 13 class Controller extends \yii\base\Controller
 14 {
 15     /**
 16      * @var boolean whether to enable CSRF validation for the actions in this controller.
 17      * @var boolean 是否启动CSRF验证标记
 18      * CSRF validation is enabled only when both this property and [[Request::enableCsrfValidation]] are true.
 19      */
 20     public $enableCsrfValidation = true;
 21     /**
 22      * @var array the parameters bound to the current action.
 23      * @var array 绑定到当前操作的参数
 24      */
 25     public $actionParams = [];
 26 
 27 
 28     /**
 29      * Renders a view in response to an AJAX request.
 30      * 这个渲染的结果用来作为ajax请求的的响应
 31      *
 32      * This method is similar to [[renderPartial()]] except that it will inject into
 33      * the rendering result with JS/CSS scripts and files which are registered with the view.
 34      * For this reason, you should use this method instead of [[renderPartial()]] to render
 35      * a view to respond to an AJAX request.
 36      * 这个方法和renderPartial类似,但这个返回的结果中会包含css/js以及其它在view中注册的文件。
 37      *
 38      * @param string $view the view name. Please refer to [[render()]] on how to specify a view name.
 39      * @param array $params the parameters (name-value pairs) that should be made available in the view.
 40      * @return string the rendering result.
 41      */
 42     public function renderAjax($view, $params = [])
 43     {
 44         return $this->getView()->renderAjax($view, $params, $this);
 45     }
 46 
 47     /**
 48      * Binds the parameters to the action.
 49      * 基类的 action 中绑定参数功能的实现
 50      * This method is invoked by [[\yii\base\Action]] when it begins to run with the given parameters.
 51      * This method will check the parameter names that the action requires and return
 52      * the provided parameters according to the requirement. If there is any missing parameter,
 53      * an exception will be thrown.
 54      * 根据action中定义的参数,从$_GET中取对应的值,
 55      * 如果没有,则抛出异常
 56      * @param \yii\base\Action $action the action to be bound with parameters
 57      * @param array $params the parameters to be bound to the action
 58      * @return array the valid parameters that the action can run with.
 59      * @throws BadRequestHttpException if there are missing or invalid parameters.
 60      */
 61     public function bindActionParams($action, $params)
 62     {
 63         if ($action instanceof InlineAction) {//如果action继承InlineAction
 64             $method = new \ReflectionMethod($this, $action->actionMethod);//通过反射得到动作action的方法信息
 65         } else {
 66             $method = new \ReflectionMethod($action, ‘run‘);//如果action继承Action基类,通过反射得到动作action的方法信息,并实现里面的run方法
 67         }
 68 
 69         $args = [];
 70         $missing = [];
 71         $actionParams = [];
 72         foreach ($method->getParameters() as $param) {
 73              //获取在action中定义的参数的名称
 74             $name = $param->getName();
 75             if (array_key_exists($name, $params)) {
 76                 if ($param->isArray()) {//如果参数是数组类型的,如果从传入的参数中取得的数据是数组则返回,否则将得到的参数转换为数组
 77                     $args[] = $actionParams[$name] = (array) $params[$name];
 78                 } elseif (!is_array($params[$name])) {//如果不是数组,直接返回传入的参数中对应的结果
 79                     $args[] = $actionParams[$name] = $params[$name];
 80                 } else {
 81                     throw new BadRequestHttpException(Yii::t(‘yii‘, ‘Invalid data received for parameter "{param}".‘, [
 82                         ‘param‘ => $name,
 83                     ]));
 84                 }
 85                 unset($params[$name]);
 86             } elseif ($param->isDefaultValueAvailable()) { //如果默认有默认值取默认值
 87                 $args[] = $actionParams[$name] = $param->getDefaultValue();
 88             } else {//action中定义的参数没有在传入的参数中找到,标记的missing中
 89                 $missing[] = $name;
 90             }
 91         }
 92 
 93         if (!empty($missing)) {//action中的参数有缺少,抛出异常
 94             throw new BadRequestHttpException(Yii::t(‘yii‘, ‘Missing required parameters: {params}‘, [
 95                 ‘params‘ => implode(‘, ‘, $missing),
 96             ]));
 97         }
 98 
 99         $this->actionParams = $actionParams;
100 
101         return $args;
102     }
103 
104     /**
105      * @inheritdoc  重写基类的beforeAction
106      */
107     public function beforeAction($action)
108     {
109         if (parent::beforeAction($action)) {
110             //父类的beforAction方法执行成功后,启动csrf验证功能
111             if ($this->enableCsrfValidation && Yii::$app->getErrorHandler()->exception === null && !Yii::$app->getRequest()->validateCsrfToken()) {
112                 throw new BadRequestHttpException(Yii::t(‘yii‘, ‘Unable to verify your data submission.‘));
113             }
114             return true;
115         }
116         
117         return false;
118     }
119 
120     /**
121      * Redirects the browser to the specified URL.
122      * 重定向方法[[Response::redirect()]]的短方法
123      * This method is a shortcut to [[Response::redirect()]].
124      *
125      * You can use it in an action by returning the [[Response]] directly:
126      * 下面的例子是重定向到longin
127      * ```php
128      * // stop executing this action and redirect to login page
129      * return $this->redirect([‘login‘]);
130      * ```
131      *
132      * @param string|array $url the URL to be redirected to. This can be in one of the following formats:
133      * @param string|array $url 重定向的URL,有下列三种形式
134      *
135      * - a string representing a URL (e.g. "http://example.com")
136      *   一个字符串URL
137      * - a string representing a URL alias (e.g. "@example.com")
138      *   别名形式的URL
139      * - an array in the format of `[$route, ...name-value pairs...]` (e.g. `[‘site/index‘, ‘ref‘ => 1]`)
140      *   数组,第一个元素为生成路径的参数,后面的元素为链接中传递的参数
141      *   [[Url::to()]] will be used to convert the array into a URL.
142      *
143      * Any relative URL will be converted into an absolute one by prepending it with the host info
144      * of the current request.
145      * 如果传入的是相对的url,都会根据当前请求的host info 转换为绝对url
146      *
147      * @param integer $statusCode the HTTP status code. Defaults to 302.
148      * See 
149      * for details about HTTP status code
150      * @return Response the current response object
151      */
152     public function redirect($url, $statusCode = 302)
153     {
154         return Yii::$app->getResponse()->redirect(Url::to($url), $statusCode);
155     }
156 
157     /**
158      * Redirects the browser to the home page.
159      * 重定向到首页
160      *
161      * You can use this method in an action by returning the [[Response]] directly:
162      *
163      * ```php
164      * // stop executing this action and redirect to home page
165      * return $this->goHome();
166      * ```
167      *
168      * @return Response the current response object
169      */
170     public function goHome()
171     {
172         return Yii::$app->getResponse()->redirect(Yii::$app->getHomeUrl());
173     }
174 
175     /**
176      * Redirects the browser to the last visited page.
177      * 返回上一页
178      *
179      * You can use this method in an action by returning the [[Response]] directly:
180      *
181      * ```php
182      * // stop executing this action and redirect to last visited page
183      * return $this->goBack();
184      * ```
185      *
186      * For this function to work you have to [[User::setReturnUrl()|set the return URL]] in appropriate places before.
187      *
188      * @param string|array $defaultUrl the default return URL in case it was not set previously.
189      * If this is null and the return URL was not set previously, [[Application::homeUrl]] will be redirected to.
190      * Please refer to [[User::setReturnUrl()]] on accepted format of the URL.
191      * @return Response the current response object
192      * @see User::getReturnUrl()
193      */
194     public function goBack($defaultUrl = null)
195     {
196         return Yii::$app->getResponse()->redirect(Yii::$app->getUser()->getReturnUrl($defaultUrl));
197     }
198 
199     /**
200      * Refreshes the current page.
201      * 刷新页面
202      * This method is a shortcut to [[Response::refresh()]].
203      *
204      * You can use it in an action by returning the [[Response]] directly:
205      *
206      * ```php
207      * // stop executing this action and refresh the current page
208      * return $this->refresh();
209      * ```
210      *
211      * @param string $anchor the anchor that should be appended to the redirection URL.
212      * Defaults to empty. Make sure the anchor starts with ‘#‘ if you want to specify it.
213      * @return Response the response object itself
214      */
215     public function refresh($anchor = ‘‘)
216     {
217         return Yii::$app->getResponse()->redirect(Yii::$app->getRequest()->getUrl() . $anchor);
218     }
219 }

 

本类排行

今日推荐

热门手游