Yii Framework Official Guide Series 7--Basics: Controllers

Source: Internet
Author: User
Tags yii



A controller is an instance of Ccontroller or its subclasses. It is created by the app when the user requests it. When a controller is running, it performs the requested action, and the action usually introduces the necessary model and renders the corresponding view. The simplest form of action is a controller class method whose name begins with action.

The controller usually has a default action. The default action is executed when the user's request does not specify an action to perform. By default, the default action name is index. It can be modified by setting Ccontroller::d efaultaction.

The following is the simplest code required for a controller class. Because this controller does not define any actions, the request to it throws an exception.


Class Sitecontroller extends ccontroller{}

1. Routing

Controllers and actions are identified by ID. The controller ID is a ' path/to/xyz ' format that corresponds 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 name of the action method that removes the action prefix. For example, if a controller class contains a method named Actionedit, the corresponding action ID is edit.

Note: before the 1.0.3 version, the controller ID is in PATH.TO.XYZ format, not path/to/xyz.

The user requests a specific controller and action in the form of a route. The route is connected by the controller ID and the action ID, and the two are separated by a slash. For example, 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 with version 1.0.1, you can make the route insensitive to case by setting the curlmanager::casesensitive in the app configuration to False . When in case insensitive mode, make sure that you follow the appropriate rules conventions, that is, the directory name that contains the controller class file is lowercase, and the keys used in the controller mapping and action map are lowercase.

Starting with the 1.0.3 version, the application can contain modules (module). In the module, the routing format for the controller action is Moduleid/controllerid/actionid. For more information, please read the section on modules.

2. Controller instantiation

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

    • If Cwebapplication::catchallrequest is specified, the controller is created based on this attribute, and the user-specified controller ID is ignored. This is typically used to set the app to maintain state and display a static prompt page .

    • If an ID is found in Cwebapplication::controllermap, the corresponding controller configuration is used to create the controller instance.

    • If the ID is ' path/to/xyz ' format, the controller class name will be judged as Xyzcontroller, the corresponding class file is 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 exception is triggered.

The above procedure is slightly different after using the module (available after version 1.0.3). Specifically, the app checks whether this ID represents a controller in a module. If so, the module instance is created first and then the controller instance in the module is created .

3. Action

As mentioned earlier, an action can be defined as a method named with the action Word as the prefix. The more advanced way is to define an action class and have the controller instantiate it when it receives the request. This allows the action to be reused, improving the 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 for the controller to notice this action, we will 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, 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 the style of the module. 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

Starting with version 1.1.4, YII provides support for automatic action parameter binding. That is, the controller action can define named parameters, and the values of the parameters will be automatically populated from $_get by Yii.

To explain this feature in detail, suppose 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 (post) is to be posted.

    • Language: A string that represents the language code used by the post.

When extracting parameters from $_get, we can no longer have this 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 Parameters feature, we can accomplish the task more easily:


Class Postcontroller extends ccontroller{public    function Actioncreate ($category, $language = ' en ')    {        $ category= (int) $category;        ... fun code starts here ...    }}

Note that we have added two parameters to the action method Actioncreate. The names of these parameters must be the same as the names we want to extract from the $_get . This parameter uses the default value of EN when the user does not specify $language parameter in the request. Because the $category does not have a default value, a chttpexception (Error code 400) exception will be thrown automatically if the user does not provide the category parameter in $_get. Starting with version 1.1.5, YII also supports action parameter bindings for array types. This is done by using PHP's type constraints, as in the following syntax:


Class Postcontroller extends ccontroller{public    function actioncreate (array $categories)    {        //YII would Make sure $categories is an array    }}

This means that we added the array keyword before the $categories in the method parameter declaration. In this case, if $_get[' categories ' is just a simple string, it will be converted to an array containing the string.

Note: If the parameter declaration does not have an array type constraint, it means that the parameter must be scalar (i.e., not an array). In this case, passing an array parameter through $_get will throw an HTTP exception.

4. Filter

A filter is a piece of code that can be configured to execute before or after the controller action executes. For example, the access control filter will be executed to ensure that the user has been authenticated before the requested action is performed, and the performance filter can be used to measure the time taken by the controller to execute.

An action can have multiple filters. The filter execution order is the order in which they appear in the filter list. Filters can block actions and other filter executions in the back

A filter can be defined as a method of a controller class. The method name must begin with filter. For example, an existing Filteraccesscontrol method defines a filter named AccessControl. The filter method must be of the following structure:


Public Function Filteraccesscontrol ($filterChain) {    //calls $filterChain->run () to continue the execution of subsequent filters and actions. }

The $filterChain (filter chain) is an instance of Cfilterchain that represents the list of filters associated with the requested action. In the filter method, we can call $filterChain->run () to continue with subsequent filters and actions.

A filter can also be an instance of a cfilter or its subclasses. The following code defines a new filter class:


Class Performancefilter extends cfilter{    protected function prefilter ($filterChain)    {        //The logic applied before the action is executed return        true;//If the action should not be executed, this returns false    }    protected function Postfilter ($filterChain)    {        //logic applied after action execution    }}

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


Class Postcontroller extends ccontroller{...    Public function Filters ()    {        return array (            ' postonly + edit, create ',            array (                ' Application.filters.performancefilter-edit, create ',                ' unit ' = ' second ',            ),        );    }

The code above specifies two filters: Postonly and Performancefilter. The Postonly filter is method-based (the corresponding filter method is defined in the Ccontroller), whereas the Performancefilter filter is Object-based. Path alias Application.filters.PerformanceFilter Specifies that the filter class file is Protected/filters/performancefilter. We use an array to configure the Performancefilter so that it can be used to initialize the property values of the Filter object. The value of the Unit property Performancefilter here will be initialized to second.

Using the plus minus sign, we can specify which actions should or should not apply the filter. In the code above, postonly should only be applied to the edit and create actions, and performancefilter should be applied to actions other than edit and create. If no minus sign is used in the filter configuration, this filter will be applied to all actions.

Drawings: The Run method execution of the controller

The above is the Yii Framework Official Guide Series 7--Basics: Controller content, more relevant content please pay attention to topic.alibabacloud.com (www.php.cn)!

  • Related Article

    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.