Yii Framework official guide series 7-basic knowledge: Controller

Source: Internet
Author: User
The controller is an instance of CController or its subclass. It is created by the application when the user requests it. When a controller is running, it executes the requested action. The action usually introduces the necessary model and renders the corresponding view...



The controller is an instance of CController or its subclass. It is created by the application when the user requests it. When a controller is running, it executes the requested action. The action usually introduces the necessary model and renders the corresponding view. The simplest form of an action is a controller class method whose name starts with action.

The controller usually has a default action. When the user's request does not specify the action to be executed, the default action will be executed. By default, the default action is index. It can be modified by setting CController: defaultAction.

The following is the simplest code required by a controller class. Because this controller does not define any action, an exception is thrown for its request.


class SiteController extends CController{}

1. routing

The controller and action are identified by ID. The controller ID is in the 'Path/to/XYZ' format and corresponds to the corresponding controller class file protected/controllers/path/to/XyzController. php, where the sign xyz should be replaced with the actual name (for example, post corresponds to protected/controllers/PostController. php ). action ID is the action method name that removes 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 controller ID format was path. to. xyz, instead of path/to/xyz.

The user requests specific controllers and actions in the form of routes. A route is connected by the controller ID and action ID. The two are separated by diagonal lines. For example, post/edit indicates PostController and its edit action. By default, URL # requests the controller and action.

Note:By default, routes are case-sensitive. from version 1.0.1, you can set CUrlManager: caseSensitive to false in the application configuration to make the routes not case sensitive. In case-insensitive mode, make sure that you follow the rule that the directory name containing the controller file is in lowercase, the keys used in controller ING and action ing are in lowercase.

From version 1.0.3, an application may contain modules ). In the module, the routing format of the controller action is moduleID/controllerID/actionID. For more details, see the related sections of the module.

2. Controller instantiation

The controller instance is created when the CWebApplication processes the incoming request. If the controller ID is specified, the application uses the following rules to determine the class and class file location of the controller.

  • If CWebApplication: catchAllRequest is specified, the controller is created based on this attribute, and the controller ID specified by the user is ignored. This is usually used to set the application to the maintenance status and display a static prompt page.

  • If the ID is found in CWebApplication: controllerMap, the corresponding controller configuration will be used to create a controller instance.

  • If the ID is in the 'Path/to/XYZ' format, the controller class name is regarded as XyzController, and the corresponding class file is protected/controllers/path/to/XyzController. php. For example, the controller ID admin/user will be parsed as the controller class UserController, and the class file is protected/controllers/admin/UserController. php. If the class file does not exist, a 404 CHttpException exception is triggered.

After using the module (available after version 1.0.3), the above process is slightly different. Specifically, the application will check whether this ID represents the controller in a module. If yes, the module instance will be created first, and then the controller instance in the module will be created.

3. action

As described above, an action can be defined as a method named with the action word as the prefix. The more advanced method is to define a handler class and let the controller instantiate the class when receiving the request. This allows the action to be reused, improving the reusability.

To define a new category class, the following code is available:


class UpdateAction extends CAction{    public function run()    {        // place the action logic here    }}

To let the controller notice this action, we need to overwrite 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, the path alias application. controllers. post. UpdateAction is used to specify the handler class file as protected/controllers/post/UpdateAction. php.

By writing class-based actions, we can organize applications into a module style. For example, the following directory structure can be used for organizing controller 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

Starting from version 1.1.4, Yii provides support for binding automatic action parameters. That is to say, the controller action can define the named parameter. the parameter value will be automatically filled by Yii from $ _ GET.

To describe this function in detail, assume that we need to write a create action for PostController. This action requires two parameters:

  • Category: an integer that represents the ID of the category in which the post is to be published.

  • Language: a string that represents the language code used by the Post.

When extracting parameters from $ _ GET, we can skip the following boring code:


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

Now, with the action parameter function, we can easily complete the task:


class PostController extends CController{    public function actionCreate($category, $language='en')    {        $category=(int)$category;        // ... fun code starts here ...    }}

Note that two parameters are added to actionCreate. The names of these parameters must be the same as the names we want to extract from $ _ GET. When the $ language parameter is not specified in the request, the default value en is used for this parameter. Because $ category has no default value, if you do not provide the category parameter in $ _ GET, a CHttpException (error code 400) exception is automatically thrown. Yii also supports binding array-type action parameters starting from version 1.1.5. This is implemented through PHP type constraints. The syntax is as follows:


class PostController extends CController{    public function actionCreate(array $categories)    {        // Yii will make sure $categories be an array    }}

That is to say, we added the array keyword before $ categories in the method parameter declaration. In this case, if $ _ GET ['category'] is a simple string, it will be converted into an array containing the string.

Note:If the parameter declaration does not contain the array type constraint, it means that the parameter must be a scalar (I. e., not an array ). In this case, passing an array parameter through $ _ GET will cause an HTTP exception.

4. filter

A filter is a piece of code that can be configured to be executed before or after the controller action is executed. For example, the access control filter will be executed to ensure that the user has passed authentication before the action of the request is executed; the performance filter can be used to measure the time taken by the controller for execution.

An action can have multiple filters. The filter execution sequence is the order in which they appear in the filter list. Filters can prevent the action and other filters from being executed.

A filter can be defined as a controller class method. The method name must start with "filter. For example, the existing filterAccessControl method defines a filter named accessControl. The filter method must have the following structure:


Public function filterAccessControl ($ filterChain) {// call $ filterChain-> run () to continue the subsequent filter and action execution .}

$ FilterChain is an instance of CFilterChain, representing the list of filters related to the requested action. In the filter method, we can call $ filterChain-> run () to continue to execute subsequent filters and actions.

A filter can also be a CFilter or its subclass instance. The following code defines a new filter class:


Class PerformanceFilter extends CFilter {protected function preFilter ($ filterChain) {// The Logical return true applied before the action is executed; // if the action should not be executed, returns false} protected function postFilter ($ filterChain) {// The logic of the application after the action is executed }}

To apply a filter to an action, we need to overwrite the CController: filters () method. This method should return an array of filter configurations. For example:


class PostController extends CController{    ......    public function filters()    {        return array(            'postOnly + edit, create',            array(                'application.filters.PerformanceFilter - edit, create',                'unit'=>'second',            ),        );    }}

The above code specifies two filters: postOnly and PerformanceFilter. PostOnly filters are method-based (the corresponding filter methods have been defined in CController), while performanceFilter filters are object-based. Path alias application. filters. cecefilter specifies that the filter class file is protected/filters/cecefilter. We use an array to configure PerformanceFilter so that it can be used to initialize the attribute value of the filter object. The unit attribute value of PerformanceFilter is initially set to second.

With the addition and subtraction signs, we can specify which actions should or should not apply the filter. In the above code, postOnly should be applied only to edit and create actions, while PerformanceFilter should be applied to actions other than edit and create. If the addition and subtraction signs are not used in the filter configuration, the filter is applied to all actions.

Figure: execution process of the controller's run method

The above is the Yii Framework official guide series 7-basic knowledge: Controller content. For more information, see PHP Chinese network (www.php1.cn )!

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.