Home Backend Development PHP Tutorial Detailed explanation of the operating mechanism and routing function of PHP's Yii framework_php skills

Detailed explanation of the operating mechanism and routing function of PHP's Yii framework_php skills

May 16, 2016 pm 07:56 PM
php yii routing run

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 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',
];
Copy after login

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'],
];
Copy after login

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 various 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 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 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.

Statement of this Website
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

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

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

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

PHP 8.4 Installation and Upgrade guide for Ubuntu and Debian PHP 8.4 Installation and Upgrade guide for Ubuntu and Debian Dec 24, 2024 pm 04:42 PM

PHP 8.4 brings several new features, security improvements, and performance improvements with healthy amounts of feature deprecations and removals. This guide explains how to install PHP 8.4 or upgrade to PHP 8.4 on Ubuntu, Debian, or their derivati

How To Set Up Visual Studio Code (VS Code) for PHP Development How To Set Up Visual Studio Code (VS Code) for PHP Development Dec 20, 2024 am 11:31 AM

Visual Studio Code, also known as VS Code, is a free source code editor — or integrated development environment (IDE) — available for all major operating systems. With a large collection of extensions for many programming languages, VS Code can be c

Explain JSON Web Tokens (JWT) and their use case in PHP APIs. Explain JSON Web Tokens (JWT) and their use case in PHP APIs. Apr 05, 2025 am 12:04 AM

JWT is an open standard based on JSON, used to securely transmit information between parties, mainly for identity authentication and information exchange. 1. JWT consists of three parts: Header, Payload and Signature. 2. The working principle of JWT includes three steps: generating JWT, verifying JWT and parsing Payload. 3. When using JWT for authentication in PHP, JWT can be generated and verified, and user role and permission information can be included in advanced usage. 4. Common errors include signature verification failure, token expiration, and payload oversized. Debugging skills include using debugging tools and logging. 5. Performance optimization and best practices include using appropriate signature algorithms, setting validity periods reasonably,

PHP Program to Count Vowels in a String PHP Program to Count Vowels in a String Feb 07, 2025 pm 12:12 PM

A string is a sequence of characters, including letters, numbers, and symbols. This tutorial will learn how to calculate the number of vowels in a given string in PHP using different methods. The vowels in English are a, e, i, o, u, and they can be uppercase or lowercase. What is a vowel? Vowels are alphabetic characters that represent a specific pronunciation. There are five vowels in English, including uppercase and lowercase: a, e, i, o, u Example 1 Input: String = "Tutorialspoint" Output: 6 explain The vowels in the string "Tutorialspoint" are u, o, i, a, o, i. There are 6 yuan in total

Explain late static binding in PHP (static::). Explain late static binding in PHP (static::). Apr 03, 2025 am 12:04 AM

Static binding (static::) implements late static binding (LSB) in PHP, allowing calling classes to be referenced in static contexts rather than defining classes. 1) The parsing process is performed at runtime, 2) Look up the call class in the inheritance relationship, 3) It may bring performance overhead.

How do you parse and process HTML/XML in PHP? How do you parse and process HTML/XML in PHP? Feb 07, 2025 am 11:57 AM

This tutorial demonstrates how to efficiently process XML documents using PHP. XML (eXtensible Markup Language) is a versatile text-based markup language designed for both human readability and machine parsing. It's commonly used for data storage an

What are PHP magic methods (__construct, __destruct, __call, __get, __set, etc.) and provide use cases? What are PHP magic methods (__construct, __destruct, __call, __get, __set, etc.) and provide use cases? Apr 03, 2025 am 12:03 AM

What are the magic methods of PHP? PHP's magic methods include: 1.\_\_construct, used to initialize objects; 2.\_\_destruct, used to clean up resources; 3.\_\_call, handle non-existent method calls; 4.\_\_get, implement dynamic attribute access; 5.\_\_set, implement dynamic attribute settings. These methods are automatically called in certain situations, improving code flexibility and efficiency.

PHP and Python: Comparing Two Popular Programming Languages PHP and Python: Comparing Two Popular Programming Languages Apr 14, 2025 am 12:13 AM

PHP and Python each have their own advantages, and choose according to project requirements. 1.PHP is suitable for web development, especially for rapid development and maintenance of websites. 2. Python is suitable for data science, machine learning and artificial intelligence, with concise syntax and suitable for beginners.

See all articles