Yii2 framework automatic loading mechanism learning

Source: Internet
Author: User
Tags autoload aliases first string php file yii

The automatic loading of Yii2 is divided into two parts: one is the automatic loading mechanism of Composer, and the other is the automatic loading mechanism of Yii2 framework.

Automatic Composer loading

For automatic library loading information, Composer generates a file named vendor/autoload. php. You can simply introduce this file and you will get an automatic loading support.

In the previous article, we can see the following content in the portal file:

// Introduce the autoload. php file in the vendor to automatically load the class based on the composer mechanism.
Require (_ DIR _. '/../vendor/autoload. Php ');

This series is mainly about Yii2, so the automatic Composer loading mechanism is not described here.

Available materials:

Automatic Composer loading
Automatic Composer loading-reference
Composer official website

Automatic loading mechanism of Yii2 framework

The automatic loading of the Yii2 framework is implemented through the spl_autoload_register method.

In the previous article, we can see the following content in the portal file:

// Introduce the Yii Framework file Yii. php
Require (_ DIR _. '/../vendor/yiisoft/yii2/Yii. Php ');

What is in Yii. php? How does one implement automatic loading?

The Yii. php content is as follows:

<? Php/*** Yii bootstrap file. ** @ link http://www.yiiframework.com/* @ copyright Copyright (c) 2008 Yii Software LLC * @ license http://www.yiiframework.com/license/ */require (_ DIR __. '/BaseYii. php ');/*** Yii is a helper class serving common framework functionalities. ** It extends from [[\ yii \ BaseYii] which provides the actual implementation. * By writing your own Yii class, you can customize Some functionalities of [[\ yii \ BaseYii]. ** @ author Qiang Xue <qiang.xue@gmail.com> * @ since 2.0 */class Yii extends \ yii \ BaseYii {}/ *** spl_autoload_register-registers a given function as the implementation of _ autoload ** bool spl_autoload_register ([callable $ autoload_function [, bool $ throw = true [, bool $ prepend = false]) ** registers a function to the SPL _ autoload function queue. If the functions in the queue are not activated, activate them. * If you have implemented the _ autoload () function in your program, it must be explicitly registered to the _ autoload () queue. * Because the spl_autoload_register () function replaces the _ autoload () function in Zend Engine with spl_autoload () or spl_autoload_call (). * If multiple autoload functions are required, spl_autoload_register () meets these requirements. * It actually creates a queue for the autoload function, which is executed one by one in the defined order. * In contrast, _ autoload () can be defined only once. ** Autoload_function * indicates the automatic loading function to be registered. If no parameter is provided, the default implementation function spl_autoload () of autoload is automatically registered (). ** Throw * this parameter sets whether spl_autoload_register () throws an exception when autoload_function cannot be successfully registered. ** Prepend * if it is true, spl_autoload_register () will add the function to the first of the queue, rather than the end of the queue. ** Yii registers the Yii autoload function for automatic loading. In fact, */spl_autoload_register (['yii', 'autoload'], true, true) in \ yii \ BaseYii ); // define the class name of the Yii core class and the MapYii: $ classMap = require (_ DIR __. '/classes. php '); // create the Yii dependency injection container Yii: $ Container = new yii \ di \ container ();


The main content is to introduce the BaseYii. php file, declare the Yii class, inherit the BaseYii, and then register the autoload method of Yii (actually BaseYii) to implement automatic loading. Then, a Map corresponding to the Yii core class name and file address is introduced and stored in Yii ::$ classMap. Finally, an instance of yii \ di \ Container is created and stored in Yii ::$ container.

We can see that the key code for automatic loading is:

Spl_autoload_register (['yii', 'autoload'], true, true );

Let's take a look at the implementation of the autoload method in BaseYii. Its content is as follows:

/*** Class autoload loader. * This method is invoked automatically when PHP sees an unknown class. * The method will attempt to include the class file according to the following procedure: ** 1. search in [[classMap]; * 2. if the class is namespaced (e.g. 'yii \ base \ component'), it will attempt * to include the file associated with the corresponding path alias * (e.g. '@ yii/base/Component. php '); ** This autoloader allows loading classes that follow the [PSR-4 standard] (http://www.php-fig.org/psr/psr-4/) * and have its top-level namespace or sub-namespaces defined as path aliases. ** Example: When aliases '@ yii' and' @ yii/bootstrap 'are defined, classes in the 'yii \ bootstrap 'namespace * will be loaded using the '@ yii/bootstrap' alias which points to the directory where bootstrap extensi On * files are installed and all classes from other 'yii' namespaces will be loaded from the yii framework directory. ** Also the [guide section on autoloading] (guide: concept-autoloading ). ** @ param string $ className the fully qualified class name without a leading backslash "\" * @ throws UnknownClassException if the class does not exist in the class file */public static function autoload ($ clas SName) {// automatically load the class if (isset (static: $ classMap [$ className]) {// if the class exists in $ classMap, directly use $ classFile = static: $ classMap [$ className]; // if the first string is '@', it means that the corresponding file address is an alias, convert it to the actual file address if ($ classFile [0] ===' @ ') {$ classFile = static: getAlias ($ classFile );}} elseif (strpos ($ className ,'\\')! = False) {// If '\' exists, it means that it contains namespace. You can create an alias and obtain the actual file address $ classFile = static :: getAlias ('@'. str_replace ('\', '/', $ className ). '. php ', false); // if the actual file address is not obtained or the obtained address is not a file, an empty if ($ classFile = false |! Is_file ($ classFile) {return ;}} else {return ;}// introduce the file include ($ classFile) for this class; // if the debugging mode is used, in addition, $ className is neither a class nor an interface nor a trait. if (YII_DEBUG &&! Class_exists ($ className, false )&&! Interface_exists ($ className, false )&&! Trait_exists ($ className, false) {throw new UnknownClassException ("Unable to find '$ className' in file: $ classFile. Namespace missing? ");}}



You may not know the getAlias method. This method is to convert the alias in Yii2 to the actual file address. The specific content of this method will be explained in detail later.

Here are some examples to help you understand.

If the Yii ::$ classMap value is as follows:

Yii: $ classMap = [
'App/test/test' => '/var/www/basic/webtest/Test. Php'
];

When you use the 'app/test/test' class, '/var/www/basic/webtest/Test will be automatically introduced. php' file, the project content is certainly not like this, this is just a simple example for everyone to understand.

In the above example, if you use the 'yii \ base \ component' class, it will be converted into '@ yii/base/Component. php 'Alias, and then get its file address based on the alias, introduce it.



Yii automatic loading (Autoloading)

Yii relies on the automatic class loading mechanism to locate and include the required class files. It provides a high-performance and perfect support for PSR-4 standard (Chinese) automatic loaders. The automatic loader is installed when the framework file Yii. php is introduced.

Use Yii auto-loader

To use the Yii automatic class loader, you need to follow two simple rules when creating and naming classes:

Each class must be placed under the namespace (such as foo \ bar \ MyClass ).
Each class must be saved as a separate file, and its complete path can be obtained using the following algorithm:

// $ ClassName is a complete class name with a backslash at the beginning (note: Google: fully qualified class name)
$ ClassFile = Yii: getAlias ('@'. str_replace ('\\\\', '/', $ className). '. Php ');

For example, if a class is named foo \ bar \ MyClass, the file path alias of the corresponding class will be @ foo/bar/MyClass. php. In order for this alias to be correctly resolved to the file path, one of @ foo or @ foo/bar must be the root alias.

When using basic application templates, you can place your classes under the top-level namespace app so that they can be automatically loaded by Yii without defining a new alias. This is because @ app is a pre-defined alias and class name similar to app \ components \ MyClass. Based on the algorithm we just mentioned, the AppBasePath, components, and MyClass can be correctly parsed. php path.

In the advanced application template, each logic level uses its own root alias. For example, the frontend layer uses @ frontend and the backend layer uses @ backend. Therefore, you can place the front-end class in the frontend namespace, and the latter class in the backend. In this way, these classes can be automatically loaded by Yii.


Class Map)

The Yii automatic loader supports the ing table function, which creates a ing from the class name to the class file path. When the automatic loader loads a file, it first checks whether there is any class in the ing table. If yes, the corresponding file path is directly loaded, saving further checks. This makes automatic loading of classes super fast. In fact, all Yii core classes are loaded in this way.

You can use the Yii ::$ classMap method to add classes to the ing table,

Yii: $ classMap ['foo \ bar \ myclass'] = 'path/to/MyClass. Php ';

Aliases can be used to specify the path of class files. You should set a class ing table during the boot process, so that the ing table can be ready before you use a specific class.


Use other auto-loaders

Because Yii fully supports Composer to manage dependent packages, we recommend that you also install the Composer auto-loader. If you use a third-party class library that comes with the auto-loader, you should also install them.

When you use other auto-loaders and Yii auto-loaders at the same time, you should include the Yii. php file after other auto-loaders are installed successfully. This will make Yii the first automatic loader to respond to any class of automatic loading requests. For example, the following code is extracted from the script entry of the basic application template. The Composer auto-loader is installed in the first line, and the second line is the Yii auto-loader:

Require (_ DIR _. '/../vendor/autoload. Php ');
Require (_ DIR _. '/../vendor/yiisoft/yii2/Yii. Php ');

You can also use the Composer auto load instead of the Yii auto load. However, in this case, the loading efficiency of the class will decrease, and you must follow the rules set by Composer so that your class can be automatically loaded.

Supplement: if you do not want to use the Yii auto-loader, you must create a Yii. php file of your own version and include it in your script.

Auto-load extension class

The Yii automatic loader supports automatic loading of extended classes. The only requirement is that it must correctly define the autoload part in the composer. json file. Refer to the Composer document (in Chinese) to learn more about how to correctly describe autoload.

When you do not use the Yii auto-loader, the Composer auto-loader can still help you automatically load extended classes.

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.