Home  >  Article  >  Backend Development  >  Detailed explanation of the operating mechanism of PHP's Yii framework and its routing function, yii operating mechanism_PHP tutorial

Detailed explanation of the operating mechanism of PHP's Yii framework and its routing function, yii operating mechanism_PHP tutorial

WBOY
WBOYOriginal
2016-07-12 08:56:50721browse

Detailed explanation of the operating mechanism of PHP's Yii framework and its routing function, yii operating mechanism

Overview of the operating mechanism
Every time the Yii application starts processing an HTTP request, it will go through an approximate process.

  • The user submits a request to the entry script web/index.php.
  • The entry script will load the configuration array and create an application instance to handle the request.
  • The application will resolve the requested route through the request application component.
  • The application creates a controller instance to specifically handle the request.
  • The controller will create an action instance and execute the relevant Filters (access filters) for the action.
  • If any filter fails validation, the action will be cancelled.
  • If all filters pass, the action will be executed.
  • The action will load a data model, usually from the database.
  • The action renders a View and provides it with the required data model.
  • The rendered result will be returned to the response application component.
  • Responsive components will send the rendering results back to the user's browser.

The diagram below shows how the application handles a request.

2016317145658183.png (1144×876)

Bootstrapping
Boot bootstrap refers to a process of preparing the environment in advance before the application starts parsing and processing new accepted requests. Startup guidance will be carried out in two places: entry script (Entry Script) and application body (application).

In the entry script, you need to register the class file autoloader (Class Autoloader, referred to as autoloader) of each class library. This mainly includes the Composer autoloader, which is loaded via its autoload.php file, and the Yii autoloader, which is loaded via the Yii class. The entry script then loads the application's configuration and creates an instance of the application principal.

In the constructor of the application body, the following guidance work will be performed:

  • Call the yiibaseApplication::preInit() (pre-initialization) method to configure some high-priority application attributes, such as the yiibaseApplication::basePath attribute.
  • Register yiibaseApplication::errorHandler.
  • Initialize the properties of the application through the given application configuration.
  • By calling the yiibaseApplication::init() (initialization) method, it will sequentially call yiibaseApplication::bootstrap() to run the bootstrap component.
  • Load the extension manifest file vendor/yiisoft/extensions.php.
  • Create and run the bootstrap components declared by each extension.
  • Create and run each application component and each module component (if any) declared in the application's Bootstrap attribute.

Because bootstrapping must be done before each request is processed, it is extremely important to make this process as lightweight as possible and optimize this step as much as possible.

Please try not to register too many boot components. You only need to use it if it needs to work throughout the entire life cycle of HTTP request processing. To give an example of its use: if a module needs to register additional URL parsing rules, it should be listed in the bootstrap attribute of the application, so that the URL parsing rules can take effect before parsing the request. (Annotation: In other words, for performance needs, except for a few operations such as URL parsing, most components should be loaded on demand rather than all during the boot process.)

In a production environment, bytecode caching, such as APC, can be turned on to further minimize the time required to load and parse PHP files.

Some large applications contain very complex application configurations that are split into many smaller configuration files. At this point, you can consider caching the entire configuration array and loading it directly from the cache before the entry script creates the application instance.


Yii entry file
A third-party configuration management plug-in is used here: marcovwout to manage Yii configuration. I won’t go into the details. All that's left is some basic global variable settings. Pass the configuration array into Yii::createWebApplication, and then call the run method. Is a web application just running? Yes, abstraction to the highest level is like this: I pass the corresponding configuration into a container, and then The application can run normally based on this configuration.
Let’s talk about two important methods in YiiBase (import, autoload)

2016317145740223.png (561×219)

A third-party configuration management plug-in is used here: marcovwout to manage Yii configuration. I won’t go into the details. All that's left is some basic global variable settings. Pass the configuration array into Yii::createWebApplication, and then call the run method. Is a web application just running? Yes, abstraction to the highest level is like this: I pass the corresponding configuration into a container, and then The application can run normally based on this configuration.

Routing
When the entry script calls the yiiwebApplication::run() method, the first operation it performs is to parse the input request, and then instantiate the corresponding controller operation to process the request. This process is called routing. (Translation note: It is both a verb and a noun in Chinese)

Resolve routing

The first step in routing guidance is to parse the incoming request into a route. As we described in the Controllers chapter, a route is an address used to locate controller actions. This process is implemented through the yiiwebRequest::resolve() method of the request application component, which calls the URL manager to perform the actual request resolution.

By default, incoming requests include a GET parameter named r, and its value is treated as the route. But if you enable yiiwebUrlManager::enablePrettyUrl, more processing occurs when determining the route of the request. Please refer to the URL parsing and generation chapter for specific details.

If a route cannot be determined in the end, the request component will throw a yiiwebNotFoundHttpException exception (Annotation: the famous 404).

Default route

If the incoming request does not provide a specific route, (usually this is mostly a request for the home page) the default route specified by the yiiwebApplication::defaultRoute attribute will be enabled. The default value for this property is site/index, which points to the index action of the site controller. You can adjust the value of this property in the application configuration like this:

return [
  // ...
  'defaultRoute' => 'main/index',
];

catchAll routing (full interception routing)

Sometimes, you will want to temporarily put your web application into maintenance mode, so that the same information page will be displayed on all requests. Of course, there are many ways to achieve this. The simplest and fastest way is to set the yiiwebApplication::catchAll attribute in the application configuration:

return [
  // ...
  'catchAll' => ['site/offline'],
];

The catchAll attribute needs to pass in an array as a parameter. The first element of the array is the route, and the remaining elements will specify the parameters bound to the operation (in the form of name-value pairs).

When the catchAll attribute is set, it replaces all routes parsed from the incoming request. With this setup, the action used to handle all incoming requests will be the same site/offline.

Create operation

Once the request route is determined, the next step is to create an "action" object to respond to the route.

Routes can be split into multiple component fragments using the slashes inside. For example, site/index can be decomposed into two parts: site and index. Each fragment is an ID pointing to a module, controller, or action.

Starting from the first fragment of the route, the application will go through the following process to create modules (if any), controllers, and operations:

  • Set the application body as the current module.
  • Check whether the current module’s yiibaseModule::controllerMap contains the current ID. If so, a controller object is created based on the configuration in the table, and then jumps to step five to execute subsequent fragments of the route.
  • Check whether the ID points to a module in the module list in the yiibaseModule::modules attribute of the current module. If so, a module object will be created based on the configuration in the module table, and then the newly created module will be used as the environment to jump back to step two to parse the next route.
  • Treat this ID as a controller ID and create a controller object. Use the next step to parse the remaining fragments in the route.
  • The controller will search for the current ID in its yiibaseController::actions(). If it is found, it will create an action object based on the configuration in the mapping table; otherwise, the controller will try to create an inline action corresponding to the ID and defined by an action method.

In the above steps, if any error occurs, yiiwebNotFoundHttpException will be thrown, indicating that the routing boot process has failed.

Articles you may be interested in:

  • Explanation of the definition and binding methods of behaviors in PHP's Yii framework
  • Detailed explanation of how to use Behaviors in PHP's Yii framework
  • In-depth explanation of the properties in PHP's Yii framework
  • Interpretation of the processing flow of requests and responses in PHP's Yii framework
  • Using databases in PHP's Yii framework Configuration and SQL operation example tutorials
  • Examples explaining how to handle errors and exceptions in PHP's Yii framework
  • Analysis of related operations of cookie and session functions in PHP's Yii framework
  • Brief analysis of the basic knowledge of the componentization mechanism of PHP's Yii framework
  • Examples of extended writing methods for the YiiBase entry class in PHP's Yii framework
  • In-depth analysis of the event event mechanism in PHP's Yii framework
  • Comprehensive interpretation of the logging function in PHP’s Yii framework
  • How to remove the behavior bound to components in PHP’s Yii framework

www.bkjia.comtruehttp: //www.bkjia.com/PHPjc/1111324.htmlTechArticleDetailed explanation of the operating mechanism of PHP's Yii framework and its routing function, yii operating mechanism operating mechanism overview every time Yii application starts When processing HTTP requests, it will go through a similar process. ...
Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn