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!