yii2的深入学习--自动加载机制
yii2 的自动加载分两部分,一部分是 composer 的自动加载机制,另一部分是 yii2 框架自身的自动加载机制。
composer自动加载对于库的自动加载信息,composer 生成了一个 vendor/autoload.php 文件。你可以简单的引入这个文件,你会得到一个自动加载的支持。
在之前的文章,入口文件的介绍中,我们可以看到如下内容:
// 引入 vendor 中的 autoload.php 文件,会基于 composer 的机制自动加载类require(__dir__ . '/../vendor/autoload.php');
因为这个系列主要是关于 yii2 的,所以有关 composer 自动加载机制就不在这里详细说明了。
可查阅资料:
composer 自动加载composer 自动加载-参考composer 中文官网yii2 框架的自动加载机制yii2 框架的自动加载是通过 spl_autoload_register 方法实现的。
在之前的文章,入口文件的介绍中,我们可以看到如下内容:
// 引入 yii 框架的文件 yii.phprequire(__dir__ . '/../vendor/yiisoft/yii2/yii.php');
yii.php 里究竟是什么内容?如何实现了自动加载?
下面我们来看一下,yii.php 的内容如下:
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 * @since 2.0 */class yii extends \yii\baseyii{}/** * spl_autoload_register — 注册给定的函数作为 __autoload 的实现 * * bool spl_autoload_register ([ callable $autoload_function [, bool $throw = true [, bool $prepend = false ]]] ) * * 将函数注册到spl __autoload函数队列中。如果该队列中的函数尚未激活,则激活它们。 * 如果在你的程序中已经实现了__autoload()函数,它必须显式注册到__autoload()队列中。 * 因为 spl_autoload_register()函数会将zend engine中的__autoload()函数取代为spl_autoload()或spl_autoload_call()。 * 如果需要多条 autoload 函数,spl_autoload_register() 满足了此类需求。 * 它实际上创建了 autoload 函数的队列,按定义时的顺序逐个执行。 * 相比之下, __autoload() 只可以定义一次。 * * autoload_function * 欲注册的自动装载函数。如果没有提供任何参数,则自动注册 autoload 的默认实现函数spl_autoload()。 * * throw * 此参数设置了 autoload_function 无法成功注册时, spl_autoload_register()是否抛出异常。 * * prepend * 如果是 true,spl_autoload_register() 会添加函数到队列之首,而不是队列尾部。 * * yii 注册了 yii 的 autoload 函数,实现自动加载, 其实现在 \yii\baseyii 中 */spl_autoload_register(['yii', 'autoload'], true, true);// 定义 yii 核心的 class 的类名与文件地址的 mapyii::$classmap = require(__dir__ . '/classes.php');// 创建 yii 的依赖注入的容器yii::$container = new yii\di\container();
其主要内容就是引入了 baseyii.php 文件,然后声明了类 yii,继承了 baseyii,然后注册了 yii (其实是 baseyii)的 autoload 方法,去实现自动加载。之后又引入了yii 核心类名与文件地址一一对应的 map,存储到 yii::$classmap 中。最后创建了一个 yii\di\container 的实例,存储到 yii::$container 中。
可以看出实现自动加载的关键代码是:
spl_autoload_register(['yii', 'autoload'], true, true);
下面我们来看一下 baseyii 中 autoload 方法的实现,其内容如下:
/** * 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. [email protected]/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 [email protected]` and [email protected]/bootstrap` are defined, classes in the `yii\bootstrap` namespace * will be loaded using the [email protected]/bootstrap` alias which points to the directory where bootstrap extension * 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($classname) { // 自动加载类 if (isset(static::$classmap[$classname])) { // 如果 $classmap 中存在该类,就直接使用 $classfile = static::$classmap[$classname]; // 如果第一个字符串为'@',就意味着对应的文件地址是别名,就将它转化成真实的文件地址 if ($classfile[0] === '@') { $classfile = static::getalias($classfile); } } elseif (strpos($classname, '\\') !== false) { // 如果存在'\\',就意味着含有 namespace,可以拼成别名,再根据别名获取真实的文件地址 $classfile = static::getalias('@' . str_replace('\\', '/', $classname) . '.php', false); // 没取到真是文件地址或者获取的地址不是一个文件,就返回空 if ($classfile === false || !is_file($classfile)) { return; } } else { return; } // 引入该类的文件 include($classfile); // 如果是调试模式,而且 $classname 即不是类,不是接口,也不是 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?); } }
其中,大家可能不太清楚 getalias 方法,这个方法其实就是将 yii2 中的别名转化成真实的文件地址,关于该方法的具体内容,之后会详细讲解。
举几个例子,帮助大家理解一下。
如果 yii::$classmap 的值如下:
yii::$classmap = [ 'app/test/test' => '/var/www/basic/webtest/test.php'];
当你使用 ‘app/test/test’ 类时,就会自动引入 '/var/www/basic/webtest/test.php' 文件,项目中的内容当然不是这个样子的,这只是个简单的例子,便于大家理解。
在继续上面的例子,如果你使用了‘yii\base\component’ 类,它就会转变成 ‘@yii/base/component.php’ 别名,然后在根据别名获取到它的文件地址,引入进来。
以上就是 yii2 的自动加载机制的基本内容~~
对 yii2 源码有兴趣的同学可以关注项目 yii2-2.0.3-annotated,现在在上面已经添加了不少关于 yii2 源码的注释,之后还会继续添加~
有兴趣的同学也可以参与进来,提交 yii2 源码的注释。