For more information, see Controller and yiicontroller in the Yii framework of PHP.

Source: Internet
Author: User

For more information, see Controller and yiicontroller in the Yii framework of PHP.

The Controller is part of the MVC pattern and is an object that inherits the yii \ base \ Controller class and is responsible for processing requests and generating responses. Specifically, after the controller takes over the control from the application subject, it analyzes the request data and sends it to the model, transmits the model results to the view, and finally generates the output response information.

Operation

A controller consists of operations. It is the most basic unit for executing end user requests. A controller can have one or more operations.

The following example shows the Controller post that contains two operations: view and create:

namespace app\controllers;use Yii;use app\models\Post;use yii\web\Controller;use yii\web\NotFoundHttpException;class PostController extends Controller{ public function actionView($id) {  $model = Post::findOne($id);  if ($model === null) {   throw new NotFoundHttpException;  }  return $this->render('view', [   'model' => $model,  ]); } public function actionCreate() {  $model = new Post;  if ($model->load(Yii::$app->request->post()) && $model->save()) {   return $this->redirect(['view', 'id' => $model->id]);  } else {   return $this->render('create', [    'model' => $model,   ]);  } }}

In the operation view (defined as actionView () method), the code first loads the model based on the request model ID. If the model is loaded successfully, the view named view is rendered and displayed, otherwise, an exception is thrown.

In the create (defined as actionCreate () method) operation, the code is similar. enter the request data in the model, and then save the model. If both are successful, the view operation of the newly created model with the ID is redirected. Otherwise, the create view entered by the user is displayed.

Routing

The end user finds the operation through the so-called routing. The routing is a string containing the following parts:

  • Model ID: The model ID only exists when the Controller belongs to a non-application module;
  • Controller ID: The character string that uniquely identifies the Controller under the same application (or if the module is a controller under the module;
  • Operation ID: the string that uniquely identifies an operation under the same controller.

The routing format is as follows:

ControllerID/ActionID
If the Controller belongs to the module, the following format is used:

ModuleID/ControllerID/ActionID
If the user's request address is http: // hostname/index. php? R = site/index: The index operation of the site controller is performed.

Create a controller

In the yii \ web \ Application web Application, the Controller should inherit the yii \ web \ Controller or its subclass. Similarly, in the yii \ console \ Application console Application, the Controller inherits the yii \ console \ Controller or its subclass. The following code defines a site controller:

namespace app\controllers;use yii\web\Controller;class SiteController extends Controller{}

Controller ID

Generally, the controller is used to process the resource type related to the request. Therefore, the Controller ID is usually a resource-related term. For example, use article as the controller ID for processing the article.

The Controller ID should only contain lowercase letters, numbers, underscores, horizontal bars, and forward slashes. For example, article and post-comment are true controller IDs, article ?, PostComment, admin \ post is not the Controller ID.

The Controller Id can contain the subdirectory prefix. For example, admin/article represents the article controller in the admin subdirectory of yii \ base \ Application: controllerNamespace controller. Sub-directory prefixes can be uppercase/lowercase letters, numbers, underscores, and slashes. The forward slash is used to distinguish multi-level sub-directories (such as panels/admin ).

Controller Class Name

The Controller ID follows the following rules to derive the Controller Class Name:

Converts the first letter of each word identified by a forward slash into uppercase letters. Note that if the Controller ID contains a forward slash, only the first letter after the last forward slash is converted into uppercase;
Remove the horizontal bar and replace the forward slash with the backslash;
Add the Controller suffix;
Add the yii \ base \ Application: controllerNamespace controller namespace.
For example, assume that the namespace of the yii \ base \ Application: controllerNamespace controller is app \ controllers:

  • Article corresponds to app \ controllers \ ArticleController;
  • Post-comment corresponds to app \ controllers \ PostCommentController;
  • Admin/post-comment corresponds to app \ controllers \ admin \ PostCommentController;
  • AdminPanels/post-comment corresponds to app \ controllers \ adminPanels \ PostCommentController.

The Controller class must be automatically loaded. Therefore, in the above example, the Controller article class should be in the alias @ app/controllers/ArticleController. php file definition, controller admin/post2-comment should be in @ app/controllers/admin/Post2CommentController. PHP file.

Add: The last example admin/post2-comment indicates that you can put the Controller in a subdirectory under the yii \ base \ Application: controllerNamespace controller namespace, this method is useful when you don't want to use modules to classify controllers.
Controller deployment

You can configure yii \ base \ Application: controllerMap to force the Controller ID to correspond to the class name. It is usually used on a controller that is not controlled by a third party.

Configure application configuration in application configuration as follows:

['Controllermap' => [// declare "account" Controller 'account' => 'app \ controllers \ usercontroller' with the class name ', // declare the "article" Controller 'Article' => ['class' => 'app \ controllers \ postcontroller' with the configuration array ', 'enablescsrfvalidation '=> false,]

Default Controller

Each Application has a default controller specified by the yii \ base \ Application: defaultRoute attribute. When no route is specified for a request, this attribute value is used as the route. For a yii \ web \ Application webpage Application, its value is 'SITE'. For the yii \ console \ Application console Application, its value is help, so the URL is http: // hostname/index. php indicates that the site controller handles the process.

You can modify the default controller in application configuration as follows:

[ 'defaultRoute' => 'main',]

Create operation

The create operation can be completed simply by defining the so-called Operation Method in the Controller class. The operation method must be a public method starting with action. The Return Value of the operation method is sent to the end user as the response data. The following code defines two operation indexes and hello-world:

namespace app\controllers;use yii\web\Controller;class SiteController extends Controller{ public function actionIndex() {  return $this->render('index'); } public function actionHelloWorld() {  return 'Hello World'; }}

Operation ID

Operations are usually used to perform specific operations on resources. Therefore, the Operation ID is usually a verb, such as view and update.

The operation ID must contain only lowercase letters, numbers, underscores, and hyphens (-). The hyphens (-) in the Operation ID are used to separate words. For example, view, update2, and comment-post are real operation IDs, view ?, Update Is Not The operation ID.

You can create operation IDs, inline operations, and independent operations in two ways. an inline action is An inline operation defined as a method in the Controller class. An independent operation is a class that inherits yii \ base \ Action or its subclass. Inline operations are easy to create and are preferred when reuse is not required. independent operations are the opposite. They are mainly used for reuse of multiple controllers or refactoring into extensions.

Inline operation

Inline operations refer to the operation methods we just described.

The operation method name is derived based on the Operation ID following the following rules:

  • Converts the first letter of each word into uppercase letters;
  • Remove the middle horizontal bar;
  • Add the action prefix.
  • For example, convert "index" to "actionIndex" and "hello-world" to "actionHelloWorld.

Note: The name of the operation method is case sensitive. If the method name is ActionIndex, it is not considered as an operation method. Therefore, an exception is returned when requesting the index operation. Note that the operation method must be public, private or protected methods cannot be defined as inline operations.
Because it is easy to create, inline operations are the most common operations, but if you plan to reuse the same operations in different places, or you want to reassign an operation, consider defining it as an independent operation.

Independent operation

Independent operations are defined by inheriting yii \ base \ Action or its subclass. For example, Yii \ web \ ViewAction released by yii and yii \ web \ ErrorAction are independent operations.

To use an independent operation, you must use the yii \ base \ Controller: actions () method in the Controller to declare in action map, as shown in the following example:

Public function actions () {return [// declare "error" Operation 'error' => 'yii \ web \ erroraction' with a class ', // declare the "view" Operation 'view' => ['class' => 'yii \ web \ viewaction' with the configuration array ', 'viewprefix' => '',],];}

As shown above, the Return key of the actions () method is the operation ID, and the value is the corresponding operation class name or array of operations. Unlike inline operations, an independent operation ID can contain any character as long as it is stated in the actions () method.

To create an independent operation class, you must inherit yii \ base \ Action or its subclass and implement the public method named run (). run () the role of the method is similar to the operation method, for example:

<?phpnamespace app\components;use yii\base\Action;class HelloWorldAction extends Action{ public function run() {  return "Hello World"; }}

Operation Result

The Return Value of the operation method or independent run () method is very important. It indicates the corresponding operation result.

The return value can be a response object and is sent to the end user as a response.

For a yii \ web \ Application webpage Application, the returned value can be any data, which is assigned to yii \ web \ Response: data and finally converted to a string to display the Response content.
For yii \ console \ Application console applications, the return value can be an integer, indicating that the yii \ console \ Response: exitStatus executed in the command line exits.
In the preceding example, the operation result is a string and is sent to the end user as the response data. In the following example, an operation returns a response object (because yii \ web \ Controller: redirect () method to return a response object) to jump the user's browser to a new URL.

Public function actionForward ()

{// User browser jump to http://example.com return $ this-> redirect ('HTTP: // example.com ');}

Operation Parameters

The operation method of inline operations and the run () method of independent operations can contain parameters, which are called Operation parameters. The parameter value is obtained from the request. For yii \ web \ Application web applications, the value of each operation parameter is obtained from $ _ GET, and the parameter name is used as the key; for yii \ console \ Application console applications, the operation parameters correspond to the command line parameters.

For example, the Operation view (Inline operation) declares two parameters $ id and $ version.

namespace app\controllers;use yii\web\Controller;class PostController extends Controller{  public function actionView($id, $version = null)  {    // ...  }}

The operation parameters are filled in by different parameters, as shown below:

Http: // hostname/index. php? R = post/view & id = 123: $ id will be filled with '20160901', $ version is still null because no version request parameter is available;
Http: // hostname/index. php? R = post/view & id = 123 & version = 2: $ id and $ version are respectively set to '123' and '2 '';
Http: // hostname/index. php? R = post/view: the yii \ web \ BadRequestHttpException exception is thrown because the request does not provide a parameter and the required parameter $ id is assigned;
Http: // hostname/index. php? R = post/view & id [] = 123: The yii \ web \ BadRequestHttpException exception is thrown because the $ id parameter receives a number value ['20140901'] instead of a string.
If you want operation parameters to receive array values, you must specify $ id as array, as shown below:

public function actionView(array $id, $version = null){ // ...}

If the request is http: // hostname/index. php? R = post/view & id [] = 123. The $ id parameter uses the array value ['20140901']. If the request is http: // hostname/index. php? R = post/view & id = 123, the parameter $ id will get the same array value, because the non-type '123' will be automatically converted to an array.

The preceding example describes the operation parameters of a Web application. For more information about console applications, see console commands.

Default operation

Each Controller has a default operation specified by the yii \ base \ Controller: defaultAction attribute. When a route contains only the Controller ID, the default operation of the requested Controller is used.

The default operation is index by default. to modify the default operation, simply overwrite this attribute in the Controller class, as shown below:

namespace app\controllers;use yii\web\Controller;class SiteController extends Controller{ public $defaultAction = 'home'; public function actionHome() {  return $this->render('home'); }}

Controller 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;      echo 'Category:'.$category.'/Language:'.$language;       // ... 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 supports array action parameters starting from version 1.1.5. The usage is as follows:

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

Controller Lifecycle

When processing a request, the application subject creates a controller based on the request route. The controller completes the request through the following lifecycle:

  • After the Controller is created and configured, The yii \ base \ Controller: init () method is called.
  • The Controller creates an operation object based on the requested operation ID:
  • If the operation ID is not specified, the default operation ID of yii \ base \ Controller: defaultAction is used;
  • If the operation ID is found in yii \ base \ Controller: actions (), an independent operation is created;
  • If the operation ID corresponds to the operation method, an inline operation is created;
  • Otherwise, yii \ base \ InvalidRouteException is thrown.
  • The Controller calls the beforeAction () method of the application subject, Module (if the Controller belongs to a module), and controller in order;
  • If any call returns false, beforeAction () that is not called later will be skipped and the operation will be canceled; action execution will be canceled.
  • By default, each beforeAction () method triggers a beforeAction event. In the event, you can append the event to process the event;
  • The controller performs the following operations:
  • Request data parsing and filling in operation parameters;
  • The Controller calls the afterAction () method of the controller, Module (if the Controller belongs to a module), and application subject in sequence;
  • By default, each afterAction () method triggers an afterAction event. In the event, you can append the event to process the event;
  • The application body obtains the operation result and assigns it to the response.


Best practices

In well-designed applications, the controller is very refined and contains a short operation code. If your controller is very complicated, it usually means restructuring and transferring some code to other classes.

To sum up, the Controller:

  • Access Request data;
  • Methods of the model and other service components can be called based on the request data;
  • You can use views to construct responses;
  • The request data to be processed by the model should not be processed;
  • Avoid embedding HTML or other code that is displayed in the view.
Articles you may be interested in:
  • Describes how to use the frontend resource package in the Yii framework of PHP.
  • Introduction to some advanced usage of cache in PHP Yii framework
  • In-depth analysis of the cache function in the PHP Yii framework
  • Advanced View usage in PHP Yii framework
  • Detailed description of how to create and render views in the Yii framework of PHP
  • PHP Yii framework Model learning tutorial
  • How to remove the behavior bound to a component from the Yii framework of PHP
  • Definition and binding of behavior in PHP Yii framework
  • In-depth explanation of attributes in PHP Yii framework)
  • Detailed description of PHP Yii framework extension Installation and Use

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.