Example analysis of Yii2 framework class automatic loading mechanism

  • 2021-10-11 17:50:43
  • OfStack

This paper illustrates the automatic loading mechanism of Yii2 framework classes. Share it for your reference, as follows:

In yii, the class needed to be used in the program does not need to load its class file in advance, but automatically locates and loads the class file when it is used. This efficient operation mode benefits from the automatic loading mechanism of yii.

Yii's class auto-load actually uses PHP's class auto-load, so let's take a look at PHP's class auto-load first. In PHP, when the class used in the program is not loaded, the magic method is called before reporting an error __autoload() So we can override the __autoload () method to define how to find a file based on the class name and load it if a class cannot be found. Where the __autoload () method is called the class auto-loader. When we need multiple class auto-loaders, we can use the spl_autoload_register() Method instead of __autoload () to register multiple class autoloaders, which is equivalent to having multiple __autoload () methods. The spl_autoload_register () method stores all registered class auto-loaders in a queue. You can specify that a loader is placed at the front of the queue by setting its third parameter to true to ensure that it is called first. The class auto-loading mechanism of Yii is based on the spl_autoload_register () method.

Yii class automatic loading mechanism from its entry file index. php, the file source code is as follows:


<?php
defined('YII_DEBUG') or define('YII_DEBUG', true);// Operation mode 
defined('YII_ENV') or define('YII_ENV', 'dev');// Running environment 
require(__DIR__ . '/../../vendor/autoload.php');//composer Automatically load files with the class of 
require(__DIR__ . '/../../vendor/yiisoft/yii2/Yii.php');//yii The tool class file of (containing the tool class file of yii Class automatically loads) 
require(__DIR__ . '/../../common/config/bootstrap.php');// Mainly used to execute 1 Some yii Apply booted 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 fourth and fifth lines of code in the file respectively introduce the class automatic loading file of composer and the tool class file of Yii. php. The source code of Yii. php file is as follows:


require(__DIR__ . '/BaseYii.php');
class Yii extends \yii\BaseYii
{
}
spl_autoload_register(['Yii', 'autoload'], true, true);// Registration yii Class auto-loader of 
Yii::$classMap = require(__DIR__ . '/classes.php');// Introducing the mapping of class name to class file path 
Yii::$container = new yii\di\Container();

This file defines the Yii class inherited from\ yii\ BaseYii. Line 6 of the code introduces the classes. php file, which source code:


return [
 'yii\base\Action' => YII2_PATH . '/base/Action.php',
 'yii\base\ActionEvent' => YII2_PATH . '/base/ActionEvent.php',
  ....// Omission 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',
];

As you can see by looking at its source code, this file returns a mapping array from the class name to the class file path. This array is assigned to Yii:: $classMap. Line 7 of the code calls the spl_autoload_register() Method registers a class autoloader, which is Yii::autoload() This is the class loader for yii. At the same time, by putting spl_autoload_register() The third parameter of the method is assigned to true, which puts the class loader of yii at the front of the loader queue, so when an unloaded class is accessed, the class auto loader of yii will be called first.

Let's take a look at what yii's class auto-loader Yii:: autoload () actually does. This method is actually in the yii\ BaseYii class, and the source code is as follows:


/**
 *  Class auto-loader 
 * @param type $className Name of the class to load 
 * @return type
 * @throws UnknownClassException
 */
public static function autoload($className)
{
  if (isset(static::$classMap[$className])) {// The class to load is in the   Class name => Class file path   Found in the map 
    $classFile = static::$classMap[$className];
    if ($classFile[0] === '@') {// If the class file path uses an alias, perform alias resolution to obtain the full path 
      $classFile = static::getAlias($classFile);
    }
  } elseif (strpos($className, '\\') !== false) {// The class name needs to contain '\' To meet the specifications 
    $classFile = static::getAlias('@' . str_replace('\\', '/', $className) . '.php', false);// Perform alias resolution (indicating that the class name must begin with a valid root alias) 
    if ($classFile === false || !is_file($classFile)) {
      return;
    }
  } else {
    return;
  }
  include($classFile);// Introducing class files to be loaded 
  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?");
  }
}

This method first goes to the name of the class that needs to be loaded Yii::$classMap Find in this mapping array, if it exists, introduce the corresponding class file, and if it does not exist, carry out alias resolution to get the complete file path. It also shows that if the class used is not defined in advance in YII:: $classMap, the class name must start with a valid root alias, otherwise the corresponding file cannot be found.

In this way, in yii, there is no need to load a lot of class files that may be used in advance. When a certain class is used, the class automatic loader of yii will automatically load, which is efficient and convenient!

For more readers interested in Yii related contents, please check the topics on this site: "Introduction to Yii Framework and Summary of Common Skills", "Summary of Excellent Development Framework of php", "Introduction to smarty Template", "Introduction to php Object-Oriented Programming", "Summary of Usage of php String (string)", "Introduction to php+mysql Database Operation" and "Summary of Common Database Operation Skills of php"

I hope this article is helpful to the PHP programming based on Yii framework.


Related articles: