YII2 Create controller (Createcontroller) method detailed _php instance

Source: Internet
Author: User
Tags smarty template yii

This example describes the YII2 creation controller (Createcontroller) method. Share to everyone for your reference, specific as follows:

Yii in the creation of a controller is in the application request through Urlmanager parse out the way by the information, and then by the Yii\base\module in the

Public Function Runaction ($route, $params = [])

method to create the controller, and finally the corresponding action is performed by the controller.

First, it is clear that therouting in Yii is divided into three different scenarios:

The first is with modules (module Id/controller id/action ids),

The second is a (sub dir)/controller id/action ID with a namespace (subdirectory)

The third type is only the controller and the action (Controller id/action ID)

These three have precedence, so when you create a controller, you are looking at the route of the module type first, and if so, get the module and then create the controller by this module.

Then I'll judge if it's the second namespace.

Public Function Createcontroller ($route) {//If the route is empty, use the default route if ($route = = ') {$route = $this->defaultroute
  ;
  /double slashes or leading/ending slashes may cause substr//Remove the trailing backslash ("/"), and false creation fails if the route contains "//".
  $route = Trim ($route, '/');
  if (Strpos ($route, '//')!== false) {return false; * * * Routing is divided into three cases, one is a module ID (modular Id/controller id/action ID), * One is a namespace (subdirectory) (sub dir)/controller id/action  ID) * One is only controller and action (Controller id/action ID) * So here is to be separated into two parts according to the first "/", $id and $route information, */if (Strpos ($route, '/')!==
  False) {list ($id, $route) = explode ('/', $route, 2);
    else {$id = $route;
  $route = ';
   }//module and controller map take precedence/* To see if this ID is a module, and if it is a module, then use this module to create the controller.
   * So, if a controller's name and module name are duplicated, the controller in the module will be created first.
   * If there is a url:http://www.yii2.com/index.php?r=test/index * is intended to access the controller inside the application test controller, to perform the index action. * However, if there is a module named Test, there is a indexcontroller * * * Based on the above will generate $id=test, $route =index * * * Because this module is found below, the index controller below the test module is executed, * without executing the index action of the test controller inside the application * * $modu
  Le = $this->getmodule ($id);
  if ($module!== null) {return $module->createcontroller ($route); //If the controller mapping is specified in the CONTROLLERMAP array, the controller if (Isset ($this->controllermap[$id]) will be created preferentially based on the mapping inside the {$controller = Yii::c
    Reateobject ($this->controllermap[$id], [$id, $this]);
  return [$controller, $route]; * * * If there is a "/" in the $route, that is, the original route is HOME/INDEX/AA * $id: Home (not a module) * $route: INDEX/AA * Because of the above know home is not a module, so this For the namespace (subdirectory), * * After the following processing is * $id: Home/index namespace (subdirectory) the index controller * $route under Home: AAA */if ($pos = STRR
    POS ($route, '/'))!== false) {$id. = '/'. substr ($route, 0, $pos);
  $route = substr ($route, $pos + 1);
  * * * $id: Home/index * $route: AAA/$controller = $this->createcontrollerbyid ($id);
if ($controller = = null && $route!== ') {//If the creation fails, plus route is created again as an ID    $controller = $this->createcontrollerbyid ($id. '/' .
    $route);
  $route = '; return $controller = = null?
False: [$controller, $route];

 }

There are two cases of $id in this function, one that is preceded by a namespace, and one that is directly on a controller ID.

Public Function Createcontrollerbyid ($id) {if (!preg_match ('%^[a-z0-9\\-_/]+$% ', $id)) {return null;
    * * * * If there is "/" in the $id, the front is the directory, followed by the class * */$pos = Strrpos ($id, '/');
      if ($pos = = False) {$prefix = ';
    $className = $id;
      else {$prefix = substr ($id, 0, $pos + 1);
    $className = substr ($id, $pos + 1); }//Generate Controller class Indexcontroller $className = Str_replace (",", Ucwords) (Str_replace ('-', ', ', $className)).
    ' Controller '; If there is a prefix (that is, a directory, namespace), precede the class with the namespace $className = LTrim ($this->controllernamespace. '\\' . Str_replace ('/', ' \ \ \ ', $prefix).
    $className, ' \ n ');
    If the class does not exist, or if the class name contains "-", an error occurs, if (Strpos ($className, '-')!== false | | |!class_exists ($className)) {return null;
    //Below is the creation of the class if (Is_subclass_of ($className, ' Yii\base\controller ')) {return new $className ($id, $this); } elseif (Yii_debug) {throw new Invalidconfigexception ("Controller class must extendM \\yii\\base\\Controller. ");}
    else {return null;

 }
}

The process ends, and then the action is executed by the controller that is created.

Public Function Runaction ($route, $params = [])
{
  $parts = $this->createcontroller ($route);
  if (Is_array ($parts)) {
    /** @var Controller $controller/
    list ($controller, $actionID) = $parts;
    $oldController = Yii:: $app->controller;
    Yii:: $app->controller = $controller;
    The controller executes the corresponding action
    $result = $controller->runaction ($actionID, $params);
    Yii:: $app->controller = $oldController;
    return $result;
  } else {
    $id = $this->getuniqueid ();
    throw new Invalidrouteexception (' Unable to resolve the request '. ($id = = = "" $route: $id. '/' . $route). '".');
  }
}

For more information on YII-related content, readers who are interested in this site can view the topics: Introduction to YII Framework and summary of common skills, "Summary of PHP Excellent development framework", "Smarty Template Introductory Course", "Introduction to PHP object-oriented programming", "PHP string" Summary of Usage , "Php+mysql Database operation Introduction Tutorial" and "PHP common database Operation Skills Summary"

I hope this article will help you with the PHP program design based on the YII framework.

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.