Yii2的深入学习--自动加载机制,yii2深入学习--
Yii2的深入学习--自动加载机制,yii2深入学习--
Yii2 的自动加载分两部分,一部分是 Composer 的自动加载机制,另一部分是 Yii2 框架自身的自动加载机制。
Composer自动加载
对于库的自动加载信息,Composer 生成了一个 vendor/autoload.php
文件。你可以简单的引入这个文件,你会得到一个自动加载的支持。
在之前的文章,入口文件的介绍中,我们可以看到如下内容:
<span>//</span><span> 引入 vendor 中的 autoload.php 文件,会基于 composer 的机制自动加载类</span> <span>require</span>(__DIR__ . '/../vendor/autoload.php');
因为这个系列主要是关于 Yii2 的,所以有关 Composer 自动加载机制就不在这里详细说明了。
可查阅资料:
Yii2 框架的自动加载机制
Yii2 框架的自动加载是通过 spl_autoload_register 方法实现的。
在之前的文章,入口文件的介绍中,我们可以看到如下内容:
<span>//</span><span> 引入 Yii 框架的文件 Yii.php</span> <span>require</span>(__DIR__ . '/../vendor/yiisoft/yii2/Yii.php');
Yii.php 里究竟是什么内容?如何实现了自动加载?
下面我们来看一下,Yii.php 的内容如下:
<?<span>php </span><span>/*</span><span>* * Yii bootstrap file. * * @link http://www.yiiframework.com/ * @copyright Copyright (c) 2008 Yii Software LLC * @license http://www.yiiframework.com/license/ </span><span>*/</span> <span>require</span>(__DIR__ . '/BaseYii.php'<span>); </span><span>/*</span><span>* * 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 </span><span>*/</span> <span>class</span> Yii <span>extends</span><span> \yii\BaseYii { } </span><span>/*</span><span>* * 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 中 </span><span>*/</span><span> spl_autoload_register([</span>'Yii', 'autoload'], <span>true</span>, <span>true</span><span>); </span><span>//</span><span> 定义 Yii 核心的 class 的类名与文件地址的 Map</span> Yii::<span>$classMap</span> = <span>require</span>(__DIR__ . '/classes.php'<span>); </span><span>//</span><span> 创建 Yii 的依赖注入的容器</span> Yii::<span>$container</span> = <span>new</span> yii\di\Container();
其主要内容就是引入了 BaseYii.php 文件,然后声明了类 Yii,继承了 BaseYii,然后注册了 Yii (其实是 BaseYii)的 autoload 方法,去实现自动加载。之后又引入了Yii 核心类名与文件地址一一对应的 Map,存储到 Yii::$classMap 中。最后创建了一个 yii\di\Container 的实例,存储到 Yii::$container 中。
可以看出实现自动加载的关键代码是:
spl_autoload_register(['Yii', 'autoload'], <span>true</span>, <span>true</span>);
下面我们来看一下 BaseYii 中 autoload 方法的实现,其内容如下:
<span>/*</span><span>* * 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 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 </span><span>*/</span> <span>public</span> <span>static</span> <span>function</span> autoload(<span>$className</span><span>) { </span><span>//</span><span> 自动加载类</span> <span>if</span> (<span>isset</span>(<span>static</span>::<span>$classMap</span>[<span>$className</span><span>])) { </span><span>//</span><span> 如果 $classMap 中存在该类,就直接使用</span> <span>$classFile</span> = <span>static</span>::<span>$classMap</span>[<span>$className</span><span>]; </span><span>//</span><span> 如果第一个字符串为'@',就意味着对应的文件地址是别名,就将它转化成真实的文件地址</span> <span>if</span> (<span>$classFile</span>[0] === '@'<span>) { </span><span>$classFile</span> = <span>static</span>::getAlias(<span>$classFile</span><span>); } } </span><span>elseif</span> (<span>strpos</span>(<span>$className</span>, '\\') !== <span>false</span><span>) { </span><span>//</span><span> 如果存在'\\',就意味着含有 namespace,可以拼成别名,再根据别名获取真实的文件地址</span> <span>$classFile</span> = <span>static</span>::getAlias('@' . <span>str_replace</span>('\\', '/', <span>$className</span>) . '.php', <span>false</span><span>); </span><span>//</span><span> 没取到真是文件地址或者获取的地址不是一个文件,就返回空</span> <span>if</span> (<span>$classFile</span> === <span>false</span> || !<span>is_file</span>(<span>$classFile</span><span>)) { </span><span>return</span><span>; } } </span><span>else</span><span> { </span><span>return</span><span>; } </span><span>//</span><span> 引入该类的文件</span> <span>include</span>(<span>$classFile</span><span>); </span><span>//</span><span> 如果是调试模式,而且 $className 即不是类,不是接口,也不是 trait,就抛出异常</span> <span>if</span> (YII_DEBUG && !<span>class_exists</span>(<span>$className</span>, <span>false</span>) && !<span>interface_exists</span>(<span>$className</span>, <span>false</span>) && !trait_exists(<span>$className</span>, <span>false</span><span>)) { </span><span>throw</span> <span>new</span> UnknownClassException("Unable to find '<span>$className</span>' in file: <span>$classFile</span>. Namespace missing?"<span>); } }</span>
其中,大家可能不太清楚 getAlias 方法,这个方法其实就是将 Yii2 中的别名转化成真实的文件地址,关于该方法的具体内容,之后会详细讲解。
举几个例子,帮助大家理解一下。
如果 Yii::$classMap 的值如下:
Yii::<span>$classMap</span> =<span> [ </span>'app/test/Test' => '/var/www/basic/webtest/Test.php'<span> ];</span>
当你使用 ‘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 源码的注释。

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics



Detailed explanation of jQuery reference method: Quick start guide jQuery is a popular JavaScript library that is widely used in website development. It simplifies JavaScript programming and provides developers with rich functions and features. This article will introduce jQuery's reference method in detail and provide specific code examples to help readers get started quickly. Introducing jQuery First, we need to introduce the jQuery library into the HTML file. It can be introduced through a CDN link or downloaded

How to remove the height attribute of an element with jQuery? In front-end development, we often encounter the need to manipulate the height attributes of elements. Sometimes, we may need to dynamically change the height of an element, and sometimes we need to remove the height attribute of an element. This article will introduce how to use jQuery to remove the height attribute of an element and provide specific code examples. Before using jQuery to operate the height attribute, we first need to understand the height attribute in CSS. The height attribute is used to set the height of an element

How to use PUT request method in jQuery? In jQuery, the method of sending a PUT request is similar to sending other types of requests, but you need to pay attention to some details and parameter settings. PUT requests are typically used to update resources, such as updating data in a database or updating files on the server. The following is a specific code example using the PUT request method in jQuery. First, make sure you include the jQuery library file, then you can send a PUT request via: $.ajax({u

jQuery is a fast, small, feature-rich JavaScript library widely used in front-end development. Since its release in 2006, jQuery has become one of the tools of choice for many developers, but in practical applications, it also has some advantages and disadvantages. This article will deeply analyze the advantages and disadvantages of jQuery and illustrate it with specific code examples. Advantages: 1. Concise syntax jQuery's syntax design is concise and clear, which can greatly improve the readability and writing efficiency of the code. for example,

Title: jQuery Tips: Quickly modify the text of all a tags on the page In web development, we often need to modify and operate elements on the page. When using jQuery, sometimes you need to modify the text content of all a tags in the page at once, which can save time and energy. The following will introduce how to use jQuery to quickly modify the text of all a tags on the page, and give specific code examples. First, we need to introduce the jQuery library file and ensure that the following code is introduced into the page: <

Title: Use jQuery to modify the text content of all a tags. jQuery is a popular JavaScript library that is widely used to handle DOM operations. In web development, we often encounter the need to modify the text content of the link tag (a tag) on the page. This article will explain how to use jQuery to achieve this goal, and provide specific code examples. First, we need to introduce the jQuery library into the page. Add the following code in the HTML file:

How to tell if a jQuery element has a specific attribute? When using jQuery to operate DOM elements, you often encounter situations where you need to determine whether an element has a specific attribute. In this case, we can easily implement this function with the help of the methods provided by jQuery. The following will introduce two commonly used methods to determine whether a jQuery element has specific attributes, and attach specific code examples. Method 1: Use the attr() method and typeof operator // to determine whether the element has a specific attribute

jQuery is a popular JavaScript library that is widely used to handle DOM manipulation and event handling in web pages. In jQuery, the eq() method is used to select elements at a specified index position. The specific usage and application scenarios are as follows. In jQuery, the eq() method selects the element at a specified index position. Index positions start counting from 0, i.e. the index of the first element is 0, the index of the second element is 1, and so on. The syntax of the eq() method is as follows: $("s
