Detailed explanation of Yii operating mechanism and routing
This article mainly introduces the operating mechanism and routing function of PHP's Yii framework. Yii is a heavyweight PHP framework based on components, suitable for developing large websites. Friends in need can refer to it. I hope to be helpful.
Overview of 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 to verify, the action will be cancelled.
If all filters pass, the action will be executed.
The action loads 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.
The response component will send the rendering results back to the user's browser.
The diagram below shows how the application handles a request.
Bootstrapping
Bootstrapping refers to: a pre-prepared environment before the application starts parsing and processing new accepted requests. process. 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 boot work will be performed:
Call the yii\base\Application::preInit() (pre-initialization) method to configure Some high-priority application properties, such as the yii\base\Application::basePath property.
Register yii\base\Application::errorHandler.
Initialize the properties of the application through the given application configuration.
By calling the yii\base\Application::init() (initialization) method, it will sequentially call yii\base\Application::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 processing each request, it is extremely important to make this process as lightweight as possible. Please 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 instead of all during the boot process.)
In a production environment, you can Turn on bytecode caching, such as APC, to further minimize the time required to load and parse PHP files.
Some large applications contain very complex application configurations, which 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's entry file
A third-party configuration management plug-in is used here: marcovwout to manage Yii's 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.
Talk about two important methods in YiiBase (import, autoload)
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 yii\web\Application::run() method, the first operation it performs is to parse the input request and then instantiate it The corresponding controller action handles this request. This process is called routing. (Annotation: 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 yii\web\Request::resolve() method of the request application component, which calls the URL manager to perform the actual request resolution.
By default, incoming requests will contain a GET parameter named r, and its value is treated as a route. But if you enable [[yii\web\UrlManager::enablePrettyUrl]], more processing will be done 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 yii\web\NotFoundHttpException (Translation: the famous 404).
Default route
If the incoming request does not provide a specific route, (generally this is mostly a request for the home page) this will Enables the default route specified by the yii\web\Application::defaultRoute attribute. 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 The web application is temporarily put into maintenance mode and 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 yii\web\Application::catchAll attribute in the application configuration:
return [ // ... 'catchAll' => ['site/offline'], ];
catchAll attribute needs to pass in an array as a parameter, and the first element of the array is the route , the remaining elements specify (in the form of name-value pairs) the various parameters bound to the operation.
When the catchAll attribute is set, it will replace 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 Action
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 to the current module.
Check whether the current module's yii\base\Module::controllerMap contains the current ID. If so, a controller object will be created based on the configuration in the table, and then jump to step five to execute subsequent fragments of the route.
Check whether the ID points to a module in the module list in the yii\base\Module::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 yii\base\Controller::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, a yii\web\NotFoundHttpException will be thrown, indicating that the routing boot process has failed.
Related recommendations:
##Yii2 Code automatic loading mechanism
How to load the verification code function that comes with Yii
The above is the detailed content of Detailed explanation of Yii operating mechanism and routing. For more information, please follow other related articles on the PHP Chinese website!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics

Windows operating system is one of the most popular operating systems in the world, and its new version Win11 has attracted much attention. In the Win11 system, obtaining administrator rights is an important operation. Administrator rights allow users to perform more operations and settings on the system. This article will introduce in detail how to obtain administrator permissions in Win11 system and how to effectively manage permissions. In the Win11 system, administrator rights are divided into two types: local administrator and domain administrator. A local administrator has full administrative rights to the local computer

Detailed explanation of division operation in OracleSQL In OracleSQL, division operation is a common and important mathematical operation, used to calculate the result of dividing two numbers. Division is often used in database queries, so understanding the division operation and its usage in OracleSQL is one of the essential skills for database developers. This article will discuss the relevant knowledge of division operations in OracleSQL in detail and provide specific code examples for readers' reference. 1. Division operation in OracleSQL

Apache Camel is an Enterprise Service Bus (ESB)-based integration framework that can easily integrate disparate applications, services, and data sources to automate complex business processes. ApacheCamel uses route-based configuration to easily define and manage integration processes. Key features of ApacheCamel include: Flexibility: ApacheCamel can be easily integrated with a variety of applications, services, and data sources. It supports multiple protocols, including HTTP, JMS, SOAP, FTP, etc. Efficiency: ApacheCamel is very efficient, it can handle a large number of messages. It uses an asynchronous messaging mechanism, which improves performance. Expandable

The modulo operator (%) in PHP is used to obtain the remainder of the division of two numbers. In this article, we will discuss the role and usage of the modulo operator in detail, and provide specific code examples to help readers better understand. 1. The role of the modulo operator In mathematics, when we divide an integer by another integer, we get a quotient and a remainder. For example, when we divide 10 by 3, the quotient is 3 and the remainder is 1. The modulo operator is used to obtain this remainder. 2. Usage of the modulo operator In PHP, use the % symbol to represent the modulus

Detailed explanation of Linux system call system() function System call is a very important part of the Linux operating system. It provides a way to interact with the system kernel. Among them, the system() function is one of the commonly used system call functions. This article will introduce the use of the system() function in detail and provide corresponding code examples. Basic Concepts of System Calls System calls are a way for user programs to interact with the operating system kernel. User programs request the operating system by calling system call functions

Detailed explanation of Linux's curl command Summary: curl is a powerful command line tool used for data communication with the server. This article will introduce the basic usage of the curl command and provide actual code examples to help readers better understand and apply the command. 1. What is curl? curl is a command line tool used to send and receive various network requests. It supports multiple protocols, such as HTTP, FTP, TELNET, etc., and provides rich functions, such as file upload, file download, data transmission, proxy

Detailed explanation of Promise.resolve() requires specific code examples. Promise is a mechanism in JavaScript for handling asynchronous operations. In actual development, it is often necessary to handle some asynchronous tasks that need to be executed in sequence, and the Promise.resolve() method is used to return a Promise object that has been fulfilled. Promise.resolve() is a static method of the Promise class, which accepts a

As a programming language widely used in the field of software development, C language is the first choice for many beginner programmers. Learning C language can not only help us establish the basic knowledge of programming, but also improve our problem-solving and thinking abilities. This article will introduce in detail a C language learning roadmap to help beginners better plan their learning process. 1. Learn basic grammar Before starting to learn C language, we first need to understand the basic grammar rules of C language. This includes variables and data types, operators, control statements (such as if statements,
