Explain the controller controller _php techniques in the PHP yii framework

Source: Internet
Author: User
Tags lowercase numeric value yii

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

Operation

The controller consists of operations, which are the most basic unit for executing end-user requests, and one controller can have one or more operations.

The following example displays the controller post that contains two actions 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 action view (defined as the Actionview () method), the code loads the model based on the request model ID, and if the load succeeds, renders the view with the name view and displays it, otherwise an exception is thrown.

In operation create (defined as the Actioncreate () method), the code is similar. Fill in the request data into the model, then save the model, and if both are successful, jump to the view action ID for the newly created model, or display a CREATE view that provides user input.

Routing

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

    • Model ID: Only exists in the controller is not an application module;
    • Controller ID: A string that uniquely identifies the controller under the same application (or the same module if the controller is under the module);
    • Action ID: A string that uniquely identifies the operation under the controller.

Routes use the following format:

Controllerid/actionid
If you belong to a controller under a module, use the following format:

Moduleid/controllerid/actionid
If the user's request address is Http://hostname/index.php?r=site/index, the site Controller's index action is performed.

Creating a Controller

In Yii\web\application Web application, the controller should inherit Yii\web\controller or its subclasses. Similarly in the Yii\console\application console application, the controller inherits Yii\console\controller or its subclasses. The following code defines a site controller:

namespace App\controllers;

Use Yii\web\controller;

Class Sitecontroller extends Controller
{
}

Controller ID

Typically, the controller is used to handle the resource types associated with the request, so the controller ID is usually a resource-related noun. For example, use article as the controller ID for processing articles.

The controller ID should only contain English lowercase letters, numbers, underscores, middle and forward slashes, such as article and Post-comment are true controller id,article?, Postcomment, Admin\post is not a controller ID.

The controller ID can contain a subdirectory prefix, such as admin/article on behalf of the article controller in the Admin subdirectory under the Yii\base\application::controllernamespace controller namespace. The subdirectory prefix can be English uppercase and lowercase letters, numbers, underscores, and forward slashes, where the forward slash is used to differentiate between multilevel subdirectories (such as panels/admin).

Controller class naming

The controller ID follows the following rule derived controller class name:

Capitalizes the first letter of each word that is distinguished by a forward slash. Note If the Controller ID contains a forward slash, only the first letter after the last forward slash is capitalized;
Remove the middle horizontal bar and replace the forward slash with a backslash;
Add controller suffix;
Add the Yii\base\application::controllernamespace controller namespace to the front.
Here are some examples, assuming the Yii\base\application::controllernamespace controller namespace 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 able to be loaded automatically, so in the above example, the Controller article class should be defined in the file alias @app/controllers/articlecontroller.php, the controller admin/ Post2-comment should be in the @app/controllers/admin/post2commentcontroller.php file.

Add: The last example admin/post2-comment that you can place the controller in a subdirectory under the Yii\base\application::controllernamespace controller namespace, where you don't want to use the module , this is useful in the case of classifying controllers.
Controller Deployment

You can force the above controller ID and class name to correspond by configuring Yii\base\application::controllermap, which is typically used on a controller that does not control the class name with a third party.

Configure the application configuration in the application configuration, as follows:

[
 ' Controllermap ' => [//]
  Declare "account" Controller ' account
  ' => ' App\controllers\usercontroller ' in class name,

  // Use configuration array to declare "article" Controller
  ' article ' => [
   ' class ' => ' App\controllers\postcontroller ',
   ' Enablecsrfvalidation ' => false,
  ],]
 ,
]

Default Controller

Each application has a default controller specified by the Yii\base\application::d Efaultroute property, which is used as a route when the request does not specify a route. For yii\web\application Web application, its value is ' site ', for the Yii\console\application console application, its value is help, so the URL is http://hostname/index.php Representation is handled by the site controller.

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

[
 ' Defaultroute ' => ' main ',
]

Create an action

The creation operation can simply define the so-called action method in the Controller class, and the action method must be a public method that starts with an action. The return value of the action method is sent to the end user as the response data, and the following code defines two operations index 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 ';
 }
}

Action ID

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

The action ID should contain only English lowercase letters, numbers, underscores, and dashes, and the middle bars in the action ID are used to separate the words. For example, view, Update2, Comment-post is the real operation Id,view?, update is not an action ID.

There are two ways to create an action ID, inline operations, and standalone operations. An inline action is inline operation is defined as a method in the Controller class, and a standalone operation is a class that inherits the Yii\base\action or its subclasses. Inline operations are easy to create and are used preferentially without reuse; instead, they are primarily used for multiple controller reuse, or refactoring to extensions.

Inline operation

Inline operation refers to the method of operation that we have just described.

The name of the action method is derived from the following rule according to the action ID:

    • Capitalize the first letter of each word;
    • Remove the middle horizontal bar;
    • Increase the action prefix.
    • For example, the index turns into Actionindex, Hello-world turns into Actionhelloworld.

Note: The name of the operation method is case-sensitive, if the method name Actionindex is not considered an operation method, so the request index operation will return an exception, also pay attention to the operation method must be public, private or protected methods can not be defined as inline operation.
Inline operation is the most common operation because it is easy to create, but if you plan to reuse the same action in different places, or if you want to reassign an operation, you need to consider defining it as a standalone operation.

Standalone operation

Standalone operations are defined by inheriting yii\base\action or its subclasses. For example, the Yii\web\viewaction and Yii\web\erroraction released by Yii are all standalone operations.

To use standalone operations, you need to overwrite the Yii\base\controller::actions () method with the controller in the action map, as shown in the following example:

The Public Function action ()
{return
 [
  ////class to declare ' error ' Operation
  ' error ' => ' yii\web\erroraction ',

  // Use configuration array to declare "view" Operation
  ' view ' => [
   ' class ' => ' yii\web\viewaction ', '
   viewprefix ' => ',
  ],
 ];
}

As shown above, the actions () method returns an array of the action ID, the value being the corresponding action class name, or the array configurations. Unlike inline operations, a standalone action ID can contain any character, as long as it is declared in the actions () method.

To create a standalone action class, you need to inherit yii\base\action or its subclasses and implement a publicly-owned method with the name run (), and the role of the run () method is similar to the action method, for example:

<?php
namespace app\components;

Use yii\base\action;

Class Helloworldaction extends Action
{public
 function run ()
 {return
  ' Hello world ';
 }
}

Operation results

The return value of the run () method of the action method or standalone operation is very important, and it represents the corresponding operation result.

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

For yii\web\application Web applications, the return value can be arbitrary data, assigned to Yii\web\response::d Ata, and eventually converted to a string to show the response content.
For yii\console\application console applications, the return value can be an integer representing the Yii\console\response::exitstatus exit state executed under the command line.
In the example above, the operation result is a string that is sent to the end user as the response data, and the following example shows an action that jumps the user's browser to a new URL by returning a response object (because the Yii\web\controller::redirect () method returns a response object).

Public Function Actionforward ()

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

Operation parameters

The operation method of inline operation and the run () method of independent operation can take parameters, called Operation parameters. Parameter values are obtained from the request, for the Yii\web\application Web application, the value of each operation parameter is obtained from the $_get, the parameter name as the key, and the operation parameters correspond to the command-line arguments for the Yii\console\application console application.

In the following example, the Operation view (inline operation) affirms two parameters $id and $version.

namespace App\controllers;

Use Yii\web\controller;

Class Postcontroller extends Controller
{public
  function Actionview ($id, $version = null)
  {
    //... c13/>}
}

The action arguments are filled in with different parameters, as follows:

Http://hostname/index.php?r=post/view&id=123: $id will fill in ' 123 ', $version is still null because there is no version request parameter;
http://hostname/index.php?r=post/view&id=123&version=2: $id and $version filled in ' 123 ' and ' 2 ' respectively;
Http://hostname/index.php?r=post/view: The yii\web\badrequesthttpexception exception is thrown because the request does not provide parameters to the must-assign parameter $id;
Http://hostname/index.php?r=post/view&id[]=123: The yii\web\badrequesthttpexception exception is thrown because the $id parameter receives the numeric value [' 123 '] Rather than a string.
If you want an action parameter to receive an array value, you need to specify $id as an array, as follows:

Public function Actionview (array $id, $version = null)
{
 //...
}

Now if the request is http://hostname/index.php?r=post/view&id[]=123, the parameter $id will use the array value [' 123 '] if the request is http://hostname/index.php?r= post/view&id=123, the parameter $id gets the same array value because no type of ' 123 ' automatically converts to a group.

The above example mainly describes the operation parameters of Web application, for console applications, see Console command.

Default action

Each controller has a default action specified by the Yii\base\controller::d efaultaction property, and when the route contains only the controller ID, the default action of the requested controller is used.

The default action defaults to index, and if you want to modify the default action, simply overwrite the attribute in the Controller class, as follows:

namespace App\controllers;

Use Yii\web\controller;

Class Sitecontroller extends Controller
{public
 $defaultAction = ' home ';

 Public Function Actionhome ()
 {return
  $this->render (' home ');
 }


Controller Action parameter bindings
starting with version 1.1.4, YII provides support for automatic action parameter bindings. That is, the controller action can define a named parameter, and the value of the parameter will be automatically populated from the $_get by Yii.

To illustrate 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 that the post is to be published in.
    • Language: A string that represents the language code used by the post.

When extracting parameters from the $_get, we can no longer have 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 feature, we can more 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 ...
    }
  }

Notice that we have added two parameters to the action method Actioncreate. The names of these parameters must be consistent with the names we want to extract from the $_get. This parameter uses the default value en when the user does not specify a $language parameter in the request. Because the $category does not have a default value, a chttpexception (Error code 400) exception is thrown automatically if the user does not provide the category parameter in $_get.

Starting with version 1.1.5, Yii already supports array action parameters. Use the following methods:

  Class Postcontroller extends Ccontroller
  {public
    function actioncreate (array $categories)
    {
      //Yii 'll make sure $categories being an array
    }
  }

Controller life Cycle

When a request is processed, the application principal creates a controller based on the request route, and the controller completes the request through the following life cycle:

    • After the controller is created and configured, the Yii\base\controller::init () method is invoked.
    • The controller creates an action object based on the requested action ID:
    • If the action ID is not specified, the Yii\base\controller::d efaultaction default action ID is used;
    • If an action ID is found in yii\base\controller::actions (), an independent operation is created;
    • If the action ID corresponds to the action method, an inline operation is created;
    • Otherwise, a Yii\base\invalidrouteexception exception is thrown.
    • The controller calls the application body, the module (if the controller belongs to the module) and the Beforeaction () method of the controller in order.
    • If any of the calls return False, the beforeaction () that are not invoked later are skipped and the action execution is canceled; action execution will is cancelled.
    • By default, each beforeaction () method triggers a beforeaction event in which you can append event-handling operations;
    • The controller performs the action:
    • Request data parsing and filling to operational parameters;
    • The controller, the module (if the controller belongs to the module) and the Afteraction () method of the application subject are called in order.
    • By default, each afteraction () method triggers a afteraction event in which you can append event-handling operations;
    • The application body gets the action result and assigns the value to the response.


Best Practices

In a well-designed application, the controller is concise and contains a brief operation code, and if your controller is complex, it usually means refactoring and transferring some code into other classes.

To sum up, the controller:

    • to access the request data;
    • The
    • can invoke the model's methods and other service components based on the requested data;
    • The
    • can construct a response using a view;
    • the request data that should be processed by the model should not be processed;
    • The
    • should avoid embedding HTML or other presentation code, which is best handled in the view.

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.