Describes the operating mechanism and routing function of the Yii Framework of PHP.

Source: Internet
Author: User
Tags php framework
This article mainly introduces the operating mechanism and routing function of the PHP Yii Framework. Yii is a component-based heavyweight PHP framework suitable for developing large websites. For more information, see Running Mechanism Overview
Each time the Yii application starts to process HTTP requests, it performs an approximate process.

  • The user submits a request pointing to the portal script web/index. php.
  • The entry script loads the configuration array and creates an application instance to process the request.
  • The application parses the requested route through the request application component.
  • The application creates a controller instance to process requests.
  • The controller creates an action instance and executes the related Filters (access filter) for the action ).
  • If any filter fails to be verified, this action is canceled.
  • If all the filters pass, the action is executed.
  • An action loads a data model, typically from a database.
  • The action renders a View and provides the required data model.
  • The rendered result is returned to the response application component.
  • The response component sends the rendering result back to the user's browser.

The following shows how an application processes a request.

Bootstrapping)
Start-Up Guide refers to a process of preparing the environment before the application starts parsing and processing new requests. The boot guide is executed in two places: Entry Script and application ).

In the portal script, you must register the Class file automatic loader (Class Autoloader) of each Class library ). This mainly includes the Composer auto-loader loaded through its autoload. php file and the Yii auto-loader loaded through the Yii class. Then, the portal script loads the application configuration and creates an application entity instance.

In the constructor of the application body, the following bootstrap work is performed:

  • Call the yii \ base \ Application: preInit () (pre-initialization) method to configure some high-priority Application attributes, such as the yii \ base \ Application: basePath attribute.
  • Register yii \ base \ Application: errorHandler.
  • Initialize attributes of an application based on the specified application configuration.
  • By calling the yii \ base \ Application: init () method, it will call yii \ base \ Application: bootstrap () in sequence to run the pilot component.
  • Load the extension manifest file (vendor/yiisoft/extensions. php.
  • Create and run bootstrap components ).
  • Create and run each application component and each module declared in the Bootstrap attribute of the application (if any ).

Because the bootstrap work must be performed once before each request is processed, it is important to make the process as lightweight as possible. please optimize this step as much as possible.

Try not to register too many pilot components. It is used only when it is used in all the lifecycle of HTTP request processing. For example, if a module needs to register additional URL parsing rules, it should be listed in the bootstrap attribute of the application, in this way, the URL resolution rule will take effect before the resolution request. In other words, for the sake of performance, in addition to a few operations such as URL parsing, most components should be loaded as needed rather than in the boot process .)

In the production environment, you can enable 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 divided into many smaller configuration files. In this case, you can cache the entire configuration array and load it directly from the cache before the script is used to create an application instance.


Yii entry file
Here we use a third-party configuration management plug-in: marcovwout to manage Yii configurations. The rest is some basic global variable settings. Input the configuration array to Yii: createWebApplication and call the run method. does a web application run like this? yes, it is abstracted to the highest level as follows: I input the corresponding configuration to a container, and then the application can run properly based on the configuration.
Two important methods in YiiBase (import and autoload)

Here we use a third-party configuration management plug-in: marcovwout to manage Yii configurations. The rest is some basic global variable settings. Input the configuration array to Yii: createWebApplication and call the run method. does a web application run like this? yes, it is abstracted to the highest level as follows: I input the corresponding configuration to a container, and then the application can run properly based on the configuration.

Routing
When the portal script calls the yii \ web \ Application: 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 ). In Chinese, it is both a verb and a noun)

Resolution route

The first step of route guidance is to resolve the incoming request to a route. As described in the controller section, routing is an address used to locate controller operations. This process is implemented through the yii \ web \ request: resolve () method of the Request application component. this method calls the URL manager for actual request parsing.

By default, an incoming request contains a GET parameter named r, and its value is considered as a route. However, if yii \ web \ UrlManager: enablePrettyUrl is enabled, more processing is performed when the request route is determined. For more information, see the URL parsing and generation section.

If a route cannot be determined, the request component throws the yii \ web \ NotFoundHttpException (404 ).

Default route

If the incoming request does not provide a specific route (generally, most of the requests are for the homepage), yii \ web \ Application :: the default route specified by the defaultRoute attribute. The default value of this attribute is site/index, which points to the index operation of the site controller. You can adjust the attribute value in the application configuration as follows:

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

CatchAll route (fully intercepted route)

Sometimes, you want to temporarily adjust your Web application to the maintenance mode, and all requests will display the same information page. Of course, there are many ways to achieve this. The simplest and quickest way is to set the yii \ web \ Application: catchAll attribute in the Application configuration:

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

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

When the catchAll attribute is set, it replaces all the routes parsed from the input request. If the preceding settings are used, the operations used to process all incoming requests are 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.

A route can be divided into multiple segments by a slash. for example, the site/index can be divided into two parts: site and index. Each segment is the ID of a Module, Controller, or action.

Starting from the first segment of the route, the application will create modules (if any), controllers, and operations in sequence through the following process:

  • Set the application subject to the current module.
  • Check whether the yii \ base \ Module: controllerMap of the current Module contains the current ID. If yes, a controller object will be created based on the configuration in the table, and then jump to Step 5 to execute the subsequent segment of the route.
  • Check whether the ID points to a Module in the list of modules in the yii \ base \ Module: modules attribute of the current Module. If yes, a module object will be created based on the configuration in the module table, and then the new module will be used as the environment, jumping back to step 2 to parse the next section of the route.
  • Consider this ID as the controller ID and create a controller object. Use the next step to parse the remaining segments in the route.
  • The Controller searches for the current ID in its yii \ base \ Controller: actions. If it is found, it will create an operation object based on the configuration in the ing table; otherwise, the controller will try to create an operation object corresponding to the ID, an inline action defined by an action method ).

In the above step, if any error occurs, yii \ web \ NotFoundHttpException will be thrown, indicating that the route pilot process has failed.

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.