Table of Contents
Composer自动加载
Yii2 框架的自动加载机制
Home Backend Development PHP Tutorial Yii2的深入学习-自动加载机制

Yii2的深入学习-自动加载机制

Jun 13, 2016 pm 12:26 PM
autoload nbsp yii

Yii2的深入学习--自动加载机制

Yii2 的自动加载分两部分,一部分是 Composer 的自动加载机制,另一部分是 Yii2 框架自身的自动加载机制。

Composer自动加载

对于库的自动加载信息,Composer 生成了一个 vendor/autoload.php 文件。你可以简单的引入这个文件,你会得到一个自动加载的支持。

在之前的文章,入口文件的介绍中,我们可以看到如下内容:

<span style="color: #008000;">//</span><span style="color: #008000;"> 引入 vendor 中的 autoload.php 文件,会基于 composer 的机制自动加载类</span><span style="color: #0000ff;">require</span>(__DIR__ . '/../vendor/autoload.php');
Copy after login

因为这个系列主要是关于 Yii2 的,所以有关 Composer 自动加载机制就不在这里详细说明了。

可查阅资料:

  1. Composer 自动加载
  2. Composer 自动加载-参考
  3. Composer 中文官网

Yii2 框架的自动加载机制

Yii2 框架的自动加载是通过 spl_autoload_register 方法实现的。

在之前的文章,入口文件的介绍中,我们可以看到如下内容:

<span style="color: #008000;">//</span><span style="color: #008000;"> 引入 Yii 框架的文件 Yii.php</span><span style="color: #0000ff;">require</span>(__DIR__ . '/../vendor/yiisoft/yii2/Yii.php');
Copy after login

Yii.php 里究竟是什么内容?如何实现了自动加载?

下面我们来看一下,Yii.php 的内容如下:

<span style="color: #000000;">php</span><span style="color: #008000;">/*</span><span style="color: #008000;">* * Yii bootstrap file. * * @link http://www.yiiframework.com/ * @copyright Copyright (c) 2008 Yii Software LLC * @license http://www.yiiframework.com/license/ </span><span style="color: #008000;">*/</span><span style="color: #0000ff;">require</span>(__DIR__ . '/BaseYii.php'<span style="color: #000000;">);</span><span style="color: #008000;">/*</span><span style="color: #008000;">* * 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 </span><span style="color: #008000;">*/</span><span style="color: #0000ff;">class</span> Yii <span style="color: #0000ff;">extends</span><span style="color: #000000;"> \yii\BaseYii{}</span><span style="color: #008000;">/*</span><span style="color: #008000;">* * 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 style="color: #008000;">*/</span><span style="color: #000000;">spl_autoload_register([</span>'Yii', 'autoload'], <span style="color: #0000ff;">true</span>, <span style="color: #0000ff;">true</span><span style="color: #000000;">);</span><span style="color: #008000;">//</span><span style="color: #008000;"> 定义 Yii 核心的 class 的类名与文件地址的 Map</span>Yii::<span style="color: #800080;">$classMap</span> = <span style="color: #0000ff;">require</span>(__DIR__ . '/classes.php'<span style="color: #000000;">);</span><span style="color: #008000;">//</span><span style="color: #008000;"> 创建 Yii 的依赖注入的容器</span>Yii::<span style="color: #800080;">$container</span> = <span style="color: #0000ff;">new</span> yii\di\Container();
Copy after login

其主要内容就是引入了 BaseYii.php 文件,然后声明了类 Yii,继承了 BaseYii,然后注册了 Yii (其实是 BaseYii)的 autoload 方法,去实现自动加载。之后又引入了Yii 核心类名与文件地址一一对应的 Map,存储到 Yii::$classMap 中。最后创建了一个 yii\di\Container 的实例,存储到 Yii::$container 中。

可以看出实现自动加载的关键代码是:

spl_autoload_register(['Yii', 'autoload'], <span style="color: #0000ff;">true</span>, <span style="color: #0000ff;">true</span>);
Copy after login

下面我们来看一下 BaseYii 中 autoload 方法的实现,其内容如下:

    <span style="color: #008000;">/*</span><span style="color: #008000;">*     * 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     </span><span style="color: #008000;">*/</span>    <span style="color: #0000ff;">public</span> <span style="color: #0000ff;">static</span> <span style="color: #0000ff;">function</span> autoload(<span style="color: #800080;">$className</span><span style="color: #000000;">)    {        </span><span style="color: #008000;">//</span><span style="color: #008000;"> 自动加载类</span>        <span style="color: #0000ff;">if</span> (<span style="color: #0000ff;">isset</span>(<span style="color: #0000ff;">static</span>::<span style="color: #800080;">$classMap</span>[<span style="color: #800080;">$className</span><span style="color: #000000;">])) {            </span><span style="color: #008000;">//</span><span style="color: #008000;"> 如果 $classMap 中存在该类,就直接使用</span>            <span style="color: #800080;">$classFile</span> = <span style="color: #0000ff;">static</span>::<span style="color: #800080;">$classMap</span>[<span style="color: #800080;">$className</span><span style="color: #000000;">];            </span><span style="color: #008000;">//</span><span style="color: #008000;"> 如果第一个字符串为'@',就意味着对应的文件地址是别名,就将它转化成真实的文件地址</span>            <span style="color: #0000ff;">if</span> (<span style="color: #800080;">$classFile</span>[0] === '@'<span style="color: #000000;">) {                </span><span style="color: #800080;">$classFile</span> = <span style="color: #0000ff;">static</span>::getAlias(<span style="color: #800080;">$classFile</span><span style="color: #000000;">);            }        } </span><span style="color: #0000ff;">elseif</span> (<span style="color: #008080;">strpos</span>(<span style="color: #800080;">$className</span>, '\\') !== <span style="color: #0000ff;">false</span><span style="color: #000000;">) {            </span><span style="color: #008000;">//</span><span style="color: #008000;"> 如果存在'\\',就意味着含有 namespace,可以拼成别名,再根据别名获取真实的文件地址</span>            <span style="color: #800080;">$classFile</span> = <span style="color: #0000ff;">static</span>::getAlias('@' . <span style="color: #008080;">str_replace</span>('\\', '/', <span style="color: #800080;">$className</span>) . '.php', <span style="color: #0000ff;">false</span><span style="color: #000000;">);            </span><span style="color: #008000;">//</span><span style="color: #008000;"> 没取到真是文件地址或者获取的地址不是一个文件,就返回空</span>            <span style="color: #0000ff;">if</span> (<span style="color: #800080;">$classFile</span> === <span style="color: #0000ff;">false</span> || !<span style="color: #008080;">is_file</span>(<span style="color: #800080;">$classFile</span><span style="color: #000000;">)) {                </span><span style="color: #0000ff;">return</span><span style="color: #000000;">;            }        } </span><span style="color: #0000ff;">else</span><span style="color: #000000;"> {            </span><span style="color: #0000ff;">return</span><span style="color: #000000;">;        }        </span><span style="color: #008000;">//</span><span style="color: #008000;"> 引入该类的文件</span>        <span style="color: #0000ff;">include</span>(<span style="color: #800080;">$classFile</span><span style="color: #000000;">);        </span><span style="color: #008000;">//</span><span style="color: #008000;"> 如果是调试模式,而且 $className 即不是类,不是接口,也不是 trait,就抛出异常</span>        <span style="color: #0000ff;">if</span> (YII_DEBUG && !<span style="color: #008080;">class_exists</span>(<span style="color: #800080;">$className</span>, <span style="color: #0000ff;">false</span>) && !<span style="color: #008080;">interface_exists</span>(<span style="color: #800080;">$className</span>, <span style="color: #0000ff;">false</span>) && !trait_exists(<span style="color: #800080;">$className</span>, <span style="color: #0000ff;">false</span><span style="color: #000000;">)) {            </span><span style="color: #0000ff;">throw</span> <span style="color: #0000ff;">new</span> UnknownClassException("Unable to find '<span style="color: #800080;">$className</span>' in file: <span style="color: #800080;">$classFile</span>. Namespace missing?"<span style="color: #000000;">);        }    }</span>
Copy after login

其中,大家可能不太清楚 getAlias 方法,这个方法其实就是将 Yii2 中的别名转化成真实的文件地址,关于该方法的具体内容,之后会详细讲解。

举几个例子,帮助大家理解一下。

如果 Yii::$classMap 的值如下:

Yii::<span style="color: #800080;">$classMap</span> =<span style="color: #000000;"> [    </span>'app/test/Test' => '/var/www/basic/webtest/Test.php'<span style="color: #000000;">];</span>
Copy after login

当你使用 ‘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 源码的注释。

 

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
2 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Repo: How To Revive Teammates
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Hello Kitty Island Adventure: How To Get Giant Seeds
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Solution: Your organization requires you to change your PIN Solution: Your organization requires you to change your PIN Oct 04, 2023 pm 05:45 PM

The message "Your organization has asked you to change your PIN" will appear on the login screen. This happens when the PIN expiration limit is reached on a computer using organization-based account settings, where they have control over personal devices. However, if you set up Windows using a personal account, the error message should ideally not appear. Although this is not always the case. Most users who encounter errors report using their personal accounts. Why does my organization ask me to change my PIN on Windows 11? It's possible that your account is associated with an organization, and your primary approach should be to verify this. Contacting your domain administrator can help! Additionally, misconfigured local policy settings or incorrect registry keys can cause errors. Right now

How to adjust window border settings on Windows 11: Change color and size How to adjust window border settings on Windows 11: Change color and size Sep 22, 2023 am 11:37 AM

Windows 11 brings fresh and elegant design to the forefront; the modern interface allows you to personalize and change the finest details, such as window borders. In this guide, we'll discuss step-by-step instructions to help you create an environment that reflects your style in the Windows operating system. How to change window border settings? Press + to open the Settings app. WindowsI go to Personalization and click Color Settings. Color Change Window Borders Settings Window 11" Width="643" Height="500" > Find the Show accent color on title bar and window borders option, and toggle the switch next to it. To display accent colors on the Start menu and taskbar To display the theme color on the Start menu and taskbar, turn on Show theme on the Start menu and taskbar

How to change title bar color on Windows 11? How to change title bar color on Windows 11? Sep 14, 2023 pm 03:33 PM

By default, the title bar color on Windows 11 depends on the dark/light theme you choose. However, you can change it to any color you want. In this guide, we'll discuss step-by-step instructions for three ways to change it and personalize your desktop experience to make it visually appealing. Is it possible to change the title bar color of active and inactive windows? Yes, you can change the title bar color of active windows using the Settings app, or you can change the title bar color of inactive windows using Registry Editor. To learn these steps, go to the next section. How to change title bar color in Windows 11? 1. Using the Settings app press + to open the settings window. WindowsI go to "Personalization" and then

OOBELANGUAGE Error Problems in Windows 11/10 Repair OOBELANGUAGE Error Problems in Windows 11/10 Repair Jul 16, 2023 pm 03:29 PM

Do you see "A problem occurred" along with the "OOBELANGUAGE" statement on the Windows Installer page? The installation of Windows sometimes stops due to such errors. OOBE means out-of-the-box experience. As the error message indicates, this is an issue related to OOBE language selection. There is nothing to worry about, you can solve this problem with nifty registry editing from the OOBE screen itself. Quick Fix – 1. Click the “Retry” button at the bottom of the OOBE app. This will continue the process without further hiccups. 2. Use the power button to force shut down the system. After the system restarts, OOBE should continue. 3. Disconnect the system from the Internet. Complete all aspects of OOBE in offline mode

How to enable or disable taskbar thumbnail previews on Windows 11 How to enable or disable taskbar thumbnail previews on Windows 11 Sep 15, 2023 pm 03:57 PM

Taskbar thumbnails can be fun, but they can also be distracting or annoying. Considering how often you hover over this area, you may have inadvertently closed important windows a few times. Another disadvantage is that it uses more system resources, so if you've been looking for a way to be more resource efficient, we'll show you how to disable it. However, if your hardware specs can handle it and you like the preview, you can enable it. How to enable taskbar thumbnail preview in Windows 11? 1. Using the Settings app tap the key and click Settings. Windows click System and select About. Click Advanced system settings. Navigate to the Advanced tab and select Settings under Performance. Select "Visual Effects"

Display scaling guide on Windows 11 Display scaling guide on Windows 11 Sep 19, 2023 pm 06:45 PM

We all have different preferences when it comes to display scaling on Windows 11. Some people like big icons, some like small icons. However, we all agree that having the right scaling is important. Poor font scaling or over-scaling of images can be a real productivity killer when working, so you need to know how to customize it to get the most out of your system's capabilities. Advantages of Custom Zoom: This is a useful feature for people who have difficulty reading text on the screen. It helps you see more on the screen at one time. You can create custom extension profiles that apply only to certain monitors and applications. Can help improve the performance of low-end hardware. It gives you more control over what's on your screen. How to use Windows 11

10 Ways to Adjust Brightness on Windows 11 10 Ways to Adjust Brightness on Windows 11 Dec 18, 2023 pm 02:21 PM

Screen brightness is an integral part of using modern computing devices, especially when you look at the screen for long periods of time. It helps you reduce eye strain, improve legibility, and view content easily and efficiently. However, depending on your settings, it can sometimes be difficult to manage brightness, especially on Windows 11 with the new UI changes. If you're having trouble adjusting brightness, here are all the ways to manage brightness on Windows 11. How to Change Brightness on Windows 11 [10 Ways Explained] Single monitor users can use the following methods to adjust brightness on Windows 11. This includes desktop systems using a single monitor as well as laptops. let's start. Method 1: Use the Action Center The Action Center is accessible

How to turn off private browsing authentication for iPhone in Safari? How to turn off private browsing authentication for iPhone in Safari? Nov 29, 2023 pm 11:21 PM

In iOS 17, Apple introduced several new privacy and security features to its mobile operating system, one of which is the ability to require two-step authentication for private browsing tabs in Safari. Here's how it works and how to turn it off. On an iPhone or iPad running iOS 17 or iPadOS 17, Apple's browser now requires Face ID/Touch ID authentication or a passcode if you have any Private Browsing tab open in Safari and then exit the session or app to access them again. In other words, if someone gets their hands on your iPhone or iPad while it's unlocked, they still won't be able to view your privacy without knowing your passcode

See all articles