Yii2 Framework class automatic loading using the detailed

Source: Internet
Author: User
Tags autoload autoloader yii
This time to everyone to bring YII2 Framework class automatic loading using the detailed, YII2 framework class automatic loading of the note what, the following is the actual case, together to see.

In Yii, a class that needs to be used in a program does not need to load its class file in advance, and automatically locates and loads the class file location when it is used, so that the efficient way to run it is thanks to the class auto-loading mechanism of yii.

Yii class Auto-loading actually uses the PHP class to automatically load, so let's take a look at the PHP class automatically loaded. In PHP, when the class used in the program is not loaded, the Magic method is called before the error is given, autoload() so we can rewrite the AutoLoad () method to define how to find the corresponding file and load it according to the class name when a class cannot be found. where the AutoLoad () method is called the class autoloader. When we need multiple class autoloader, we can use the spl_autoload_register() method instead of AutoLoad () to register multiple class autoloader, which is equivalent to having multiple autoload () methods. The Spl_autoload_register () method will store all registered class Autoloader in a queue, and you can specify that the loader is placed at the top of the queue by setting its third parameter to true to ensure that it is called first. The class automatic loading mechanism of YII is based on the Spl_autoload_register () method.

The class automatic loading mechanism of YII should start from its entrance file index.php, the source code of the file is as follows:

<?phpdefined (' yii_debug ') or define (' Yii_debug ', true);//run mode defined (' yii_env ') or define (' yii_env ', ' dev ');// Operating environment require (DIR. '/.. /.. /vendor/autoload.php ');//composer class automatically loads the file require (DIR. '/.. /.. /vendor/yiisoft/yii2/yii.php ');//yii's tool class file (contains the Yii class auto-load) require (DIR. '/.. /.. /common/config/bootstrap.php '), or//is used primarily to perform some YII application-guided code require (DIR. '/.. /config/bootstrap.php '); $config = Yii\helpers\arrayhelper::merge (  require (DIR. '/.. /.. /common/config/main.php '),  require (DIR. '/.. /.. /common/config/main-local.php '),  require (DIR. '/.. /config/main.php '),  require (DIR. '/.. /config/main-local.php ');(new Yii\web\application ($config))->run ();

The 4th, 5 lines of code in the file introduced the composer Class auto-loading file and Yii tool class file yii.php,yii.php file source as follows:

Require (DIR. '/baseyii.php '); class Yii extends \yii\baseyii{}spl_autoload_register ([' Yii ', ' AutoLoad '], true, true);// Class autoloader for registering Yii yii:: $classMap = require (DIR. '/classes.php ');//Mapping of class name to class file path Yii:: $container = new Yii\di\container ();

This file defines the Yii class inherits from \yii\baseyii, the code of the 6th line introduced the classes.php file, the file source:

return [' yii\base\action ' = Yii2_path. '/base/action.php ', ' yii\base\actionevent ' = Yii2_path. '/base/actionevent.php ',  ....//omit n multi-element ' yii\widgets\pjax ' = = Yii2_path. '/widgets/pjax.php ', ' yii\widgets\pjaxasset ' = Yii2_path. '/widgets/pjaxasset.php ', ' yii\widgets\spaceless ' = Yii2_path. '/widgets/spaceless.php ',];

By looking at its source code, you can see that this file returns an array of mappings from the class name to the path of the class file. This array is assigned to Yii:: $classMap. Line 7th of the code calls the spl_autoload_register() method to register a class loader, which is the class loader for Yii::autoload() yii. At the same time, the spl_autoload_register() class loader of Yii is placed at the front of the loader queue by assigning the third parameter of the method to true, so the class autoloader of Yii is called first when it accesses a class that is not loaded.

Let's take a look at what the Yii class Autoloader yii::autoload () does, and this method is actually in the Yii\baseyii class, the source code is as follows:

/** * class Autoloader * @param type $className: The name of the class to load * @return type * @throws unknownclass Exception */public static function AutoLoad ($className) {if (Isset (static:: $classMap [$className])) {//class to load in class name = =    Found in the class file path mapping $classFile = static:: $classMap [$className];    if ($classFile [0] = = = ' @ ') {//If the class file path uses an alias, the alias is parsed for the full path $classFile = Static::getalias ($classFile); }} elseif (Strpos ($className, ' \ \ ')!== false) {//The class name needs to contain ' \ ' to conform to specification $classFile = Static::getalias (' @ '). Str_replace (' \ \ ') , '/', $className).    '. php ', false);//alias parsing (stating that the class name must begin with a valid root alias) if ($classFile = = = False | |!is_file ($classFile)) {return;  }} else {return; } include ($classFile),//Introduce the class file to be loaded if (Yii_debug &&!class_exists ($className, false) &&!interface_ Exists ($className, false) &&!trait_exists ($className, False)) {throw new Unknownclassexception ("Unable to fin d ' $className ' in file: $classFile. Namespace missing ");}} 

This method first will be loaded according to the name of the class to load the Yii::$classMap mapping array to find, if there is the introduction of the corresponding class file, there is no alias parsing to get the full file path, it is also indicated that if the class used is not in Yii:: $classMap defined beforehand, The class name must begin with a valid root alias, or the corresponding file cannot be found.

In this way, in Yii, there is no need to load in the program a large heap of potentially used class files, when the use of a class, the Yii class autoloader automatically loaded, efficient and convenient!

Believe that you have read the case of this article you have mastered the method, more exciting please pay attention to the PHP Chinese network other related articles!

Recommended reading:

Php+ajax to get the news data case detailed

PHP Curl batch to implement a controllable concurrent asynchronous operation case study

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.