Home > Article > Backend Development > Yii Framework Official Guide Series 7 - Basics: Controllers
A controller is an instance of CController or its subclass. It is created by the application when requested by the user. When a controller runs, it performs the requested action, which typically introduces the necessary models and renders the corresponding views. The simplest form of action is a controller class method whose name starts with action.
Controllers usually have a default action. When the user's request does not specify an action to be performed, the default action will be performed. By default, the default action name is index. It can be modified by setting CController::defaultAction.
The following is the simplest code required for a controller class. Since this controller has no actions defined, requests to it will throw an exception.
class SiteController extends CController { }
Controllers and actions are identified by ID. The controller ID is in the format of 'path/to/xyz', corresponding to the corresponding controller class file protected/controllers/path/to/XyzController.php, where the flag xyz should be replaced with the actual name (for example, post corresponds to protected/controllers/PostController.php). The action ID is the action method name without the action prefix. For example, if a controller class contains a method named actionEdit, the corresponding action ID is edit.
Note: Before version 1.0.3, the format of the controller ID is path.to.xyz instead of path/to/xyz.
Users request specific controllers and actions in the form of routes. Routes are connected by a controller ID and an action ID, separated by a slash. For example, the route post/edit represents PostController and its edit action. By default, the URL http://www.php.cn/ requests this controller and action.
Note: By default, routing is case sensitive. Starting from version 1.0.1, you can set CUrlManager::caseSensitive in the application configuration to false makes the route case-insensitive. When in case-insensitive mode, make sure you follow the convention that directory names containing controller class files are lowercase, and that keys used in Controller Maps and Action Maps are lowercase.
Starting from version 1.0.3, applications can contain modules. In the module, the routing format of controller actions is moduleID/controllerID/actionID. For more details, please read the relevant chapters of the module.
The controller instance is created when CWebApplication handles incoming requests. When a controller ID is specified, the application will use the following rules to determine the controller's class and the location of the class file.
If CWebApplication::catchAllRequest is specified, the controller will be created based on this attribute, and the user-specified controller ID will be ignored. This is typically used to set the application to maintenance state and display a static prompt page.
If the ID is found in CWebApplication::controllerMap, the corresponding controller configuration will be used to create the controller instance.
If the ID is in the format of 'path/to/xyz', the name of the controller class will be judged to be XyzController, and the corresponding class file will be protected/controllers/path/to/XyzController .php. For example, the controller ID admin/user will be resolved to the controller class UserController, and the class file is protected/controllers/admin/UserController.php. If the class file does not exist, a 404 CHttpException will be triggered.
After using the module (available after version 1.0.3), the above process is slightly different. Specifically, the application checks whether this ID represents a controller in a module. If so, the module instance will be created first and then the controller instance in the module will be created.
As mentioned above, an action can be defined as a method named with the word action as the prefix. A more advanced way is to define an action class and have the controller instantiate it when a request is received. This allows actions to be reused, improving reusability.
To define a new action class, use the following code:
class UpdateAction extends CAction { public function run() { // place the action logic here } }
In order to get the controller’s attention To reach this action, we need to override the actions() method of the controller class in the following way:
class PostController extends CController { public function actions() { return array( 'edit'=>'application.controllers.post.UpdateAction', ); } }
as shown above , we used the path alias application.controllers.post.UpdateAction to specify the action class file as protected/controllers/post/UpdateAction.php.
By writing class-based actions, we can organize the application into a module style . For example, the following directory structure can be used to organize controller-related code:
protected/ controllers/ PostController.php UserController.php post/ CreateAction.php ReadAction.php UpdateAction.php user/ CreateAction.php ListAction.php ProfileAction.php UpdateAction.php
Action parameter binding
从版本 1.1.4 开始,Yii 提供了对自动动作参数绑定的支持。 就是说,控制器动作可以定义命名的参数,参数的值将由 Yii 自动从 $_GET 填充。
为了详细说明此功能,假设我们需要为 PostController 写一个 create 动作。此动作需要两个参数:
category: 一个整数,代表帖子(post)要发表在的那个分类的ID。
language: 一个字符串,代表帖子所使用的语言代码。
从 $_GET 中提取参数时,我们可以不再下面这种无聊的代码了:
class PostController extends CController { public function actionCreate() { if(isset($_GET['category'])) $category=(int)$_GET['category']; else throw new CHttpException(404,'invalid request'); if(isset($_GET['language'])) $language=$_GET['language']; else $language='en'; // ... fun code starts here ... } }
现在使用动作参数功能,我们可以更轻松的完成任务:
class PostController extends CController { public function actionCreate($category, $language='en') { $category=(int)$category; // ... fun code starts here ... } }
注意我们在动作方法 actionCreate 中添加了两个参数。 这些参数的名字必须和我们想要从 $_GET 中提取的名字一致。 当用户没有在请求中指定 $language 参数时,这个参数会使用默认值 en 。 由于 $category 没有默认值,如果用户没有在 $_GET 中提供 category 参数, 将会自动抛出一个 CHttpException (错误代码 400) 异常。从版本1.1.5开始, Yii还支持数组类型的动作参数绑定。 这是通过PHP的类型约束来实现的,语法如下:
class PostController extends CController { public function actionCreate(array $categories) { // Yii will make sure $categories be an array } }
也就是说我们在方法参数声明里的$categories之前添加了array关键字。这样的话,如果$_GET['categories']只是一个简单的字符串,它将会被转化为一个包含该字符串的数组。
注意: 如果参数声明没有加上 array 类型约束, 意味着参数必须是标量 (i.e., not an array)。这种情况下,通过 $_GET 传入一个数组参数将会引发HTTP异常。
过滤器是一段代码,可被配置在控制器动作执行之前或之后执行。例如, 访问控制过滤器将被执行以确保在执行请求的动作之前用户已通过身份验证;性能过滤器可用于测量控制器执行所用的时间。
一个动作可以有多个过滤器。过滤器执行顺序为它们出现在过滤器列表中的顺序。过滤器可以阻止动作及后面其他过滤器的执行
过滤器可以定义为一个控制器类的方法。方法名必须以 filter 开头。例如,现有的 filterAccessControl 方法定义了一个名为 accessControl 的过滤器。 过滤器方法必须为如下结构:
public function filterAccessControl($filterChain) { // 调用 $filterChain->run() 以继续后续过滤器与动作的执行。 }
其中的 $filterChain (过滤器链)是一个 CFilterChain 的实例,代表与所请求动作相关的过滤器列表。在过滤器方法中, 我们可以调用 $filterChain->run() 以继续执行后续过滤器和动作。
过滤器也可以是一个 CFilter 或其子类的实例。如下代码定义了一个新的过滤器类:
class PerformanceFilter extends CFilter { protected function preFilter($filterChain) { // 动作被执行之前应用的逻辑 return true; // 如果动作不应被执行,此处返回 false } protected function postFilter($filterChain) { // 动作执行之后应用的逻辑 } }
要对动作应用过滤器,我们需要覆盖 CController::filters() 方法。此方法应返回一个过滤器配置数组。例如:
class PostController extends CController { ...... public function filters() { return array( 'postOnly + edit, create', array( 'application.filters.PerformanceFilter - edit, create', 'unit'=>'second', ), ); } }
上述代码指定了两个过滤器: postOnly 和 PerformanceFilter。 postOnly 过滤器是基于方法的(相应的过滤器方法已在 CController 中定义); 而 performanceFilter 过滤器是基于对象的。路径别名application.filters.PerformanceFilter 指定过滤器类文件是protected/filters/PerformanceFilter。我们使用一个数组配置 PerformanceFilter ,这样它就可被用于初始化过滤器对象的属性值。此处 PerformanceFilter 的 unit 属性值将被初始为 second。
使用加减号,我们可指定哪些动作应该或不应该应用过滤器。上述代码中, postOnly 应只被应用于 edit 和 create动作,而 PerformanceFilter 应被应用于 除了 edit 和 create 之外的动作。 如果过滤器配置中没有使用加减号,则此过滤器将被应用于所有动作。
附图:控制器的run方法执行过程
以上就是Yii框架官方指南系列7——基础知识:控制器的内容,更多相关内容请关注PHP中文网(www.php.cn)!