Yii operating mechanism and routing details

Source: Internet
Author: User
Tags autoload autoloader php framework yii
This paper mainly introduces the operation mechanism and routing function of the YII framework of PHP, and Yii is a component-based heavyweight PHP framework, which is suitable for the development of large-scale web sites. You need a friend to refer to below. We hope to help you.

Overview of the operating mechanism
Every time a YII application starts processing an HTTP request, it makes an approximation of the process.

    • The user submits a request pointing to the portal script web/index.php.

    • The portal script loads the configuration array and creates an application instance to handle the request.

    • The application resolves the requested route through the request application component.

    • The application creates a controller (Director) instance that specifically processes the request.

    • The controller creates an action (action) instance and executes the associated Filters (Access filter) for the action.

    • If any one of the filter validation fails, the action is canceled.

    • If all filters are passed, the action will be executed.

    • The action loads a data model, typically loaded from the database.

    • The action renders a view and provides it with the data model you want.

    • The rendered result is returned to the response (response) Application component.

    • The response component sends the render results back to the user's browser.

The following shows how the application handles a request.

Boot boot (Bootstrapping)
Boot boot is the process of pre-preparing an environment before the app begins parsing and processing a new acceptance request. Boot boot is done in two places: the entry script (Entry scripts) and the application body (application).

In the portal script, you need to register the class file Autoloader (class Autoloader, or Autoloader) for each class library. This includes the Composer autoloader loaded through its autoload.php file, and the Yii autoloader loaded by the Yii class. The portal script then loads the application's configuration (config) and creates an instance of the application principal.

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

    • Call Yii\base\application::p the Reinit () (pre-initialized) method to configure some high-priority application properties, such as the Yii\base\application::basepath property.

    • Register Yii\base\application::errorhandler.

    • Initializes the app's properties with a given app configuration.

    • By calling the Yii\base\application::init () (initialize) method, it calls Yii\base\application::bootstrap () sequentially to run the boot component.

    • Load the extension manifest file (extension manifest files) vendor/yiisoft/extensions.php.

    • Create and run the boot component (bootstrap components) for each extension claim.

    • Create and run each of the application components and the individual module (modules) components (if any) declared in the app's Bootstrap property.

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

Please try not to register too many boot components. It only needs to be used if he needs to function in the entire life cycle of HTTP request processing. As an example of a module that needs to register an additional URL parsing rule, it should be listed in the application's bootstrap attribute so that the URL resolution rule takes effect before the request is resolved. In other words, for performance needs, most components should be loaded on demand, not all in the boot process, except for a few operations such as URL parsing. )

In a production environment, byte-code caches, 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 might consider caching the entire configuration array and loading it directly from the cache before the portal script creates the application instance.


Yii's entry file
A third-party configuration management plugin was used here: marcovwout, to manage the configuration of Yii, I will not say the details. All that is left is some basic global variable settings. Into the yii::createwebapplication inside the configured array, and then call the Run method, a Web application is not just running up, yes, the abstraction to the highest level is this: I put a container inside the corresponding configuration, The app can then function properly based on that configuration.
Say two more important methods in Yiibase (Import,autoload)

A third-party configuration management plugin was used here: marcovwout, to manage the configuration of Yii, I will not say the details. All that is left is some basic global variable settings. Into the yii::createwebapplication inside the configured array, and then call the Run method, a Web application is not just running up, yes, the abstraction to the highest level is this: I put a container inside the corresponding configuration, The app can then function properly based on that configuration.

Routing
When the ingress script calls the Yii\web\application::run () method, the first action it makes is to parse the input request, and then instantiate the corresponding controller action to process the request. This process is referred to as a bootstrap route (routing). (in Chinese, both verbs and nouns)

Parsing routes

The first step in routing guidance is to parse the incoming request into a route. As we described in the Controller (Controllers) section, routing is an address for locating controller operations. This process is implemented through the Yii\web\request::resolve () method of the request application component, which invokes the URL manager for a substantial request parsing effort.

By default, an incoming request contains a GET parameter named R, and its value is treated as a route. However, if Yii\web\urlmanager::enableprettyurl is enabled, more processing is done when the requested route is determined. For details, refer to the parsing and generating section of the URL.

If a route is ultimately unable to be determined, then the request component throws a Yii\web\notfoundhttpexception exception (the famous 404).

Default route

If the incoming request does not provide a specific route, (typically this is most often a request to the home page), the default route specified by the yii\web\application::d Efaultroute property is enabled at this time. 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 app configuration like this:

return [  //...  ] Defaultroute ' = ' main/index ',];

Catchall Routing (full intercept routing)

Sometimes you will want to temporarily adjust your Web app to maintenance mode, and all requests will display the same information page. There are, of course, many ways to achieve this. The simplest and quickest way to do this is to set the next Yii\web\application::catchall property in the application configuration:

return [  //...  ] Catchall ' = ' [' Site/offline '],];

The Catchall property needs to pass in an array to make the argument, the first element of the array is a route, and the remaining elements (in the form of a name value pair) specify each parameter that is bound to the operation.

When the Catchall property is set, it replaces all routes resolved from the input request. If this is the setting above, the operation to process 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.

The route can be divided into a plurality of fragments with the inside slash, for a chestnut, site/index can be decomposed into site and index two parts. Each fragment is an ID that points to a module, a controller, or an action (action).

Starting with the first fragment of the route, the application creates the module (if any), the controller, and the operation in the following sequence:

    • Sets the application body as the current module.

    • Checks whether the yii\base\module::controllermap of the current module 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 perform subsequent fragments of the route.

    • Checks whether the ID points to a module in the list of modules in the Yii\base\module::modules property in the current module. If it is, a module object is created based on the configuration in the module table, and then the next segment of the route is parsed with the newly created module as the environment, jumping back to step two.

    • Treat the ID as the controller ID and create the Controller object. Use the next step to parse the remaining fragments in the route.

    • The controller searches his yii\base\controller::actions () for the current ID. If found, it creates an action object based on the configuration in the mapping table, whereas the controller attempts to create an inline action that corresponds to that ID, defined by an action method.

In the above steps, if any errors occur, Yii\web\notfoundhttpexception will be thrown, indicating that the routing process failed.

Related recommendations:

Yii Related Query detailed

Code Auto-loading mechanism in YII2

The method of loading the verification code function of Yii's own

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.