Home Backend Development PHP Tutorial Yii2 framework class automatic loading mechanism example analysis

Yii2 framework class automatic loading mechanism example analysis

May 03, 2018 pm 03:26 PM
yii2 load mechanism

这篇文章主要介绍了Yii2框架类自动加载机制,结合实例形式分析了Yii框架类自动加载机制的原理与实现方法,需要的朋友可以参考下

本文实例讲述了Yii2框架类自动加载机制。分享给大家供大家参考,具体如下:

在yii中,程序中需要使用到的类无需事先加载其类文件,在使用的时候才自动定位类文件位置并加载之,这么高效的运行方式得益于yii的类自动加载机制。

Yii的类自动加载实际上使用的是PHP的类自动加载,所以先来看看PHP的类自动加载。在PHP中,当程序中使用的类未加载时,在报错之前会先调用魔术方法__autoload(),所以我们可以重写__autoload()方法,定义当一个类找不到的时候怎么去根据类名称找到对应的文件并加载它。其中__autoload()方法被称为类自动加载器。当我们需要多个类自动加载器的时候,我们可以使用spl_autoload_register()方法代替__autoload()来注册多个类自动加载器,这样就相当于有多个__autoload()方法。spl_autoload_register()方法会把所有注册的类自动加载器存入一个队列中,你可以通过设置它的第三个参数为true来指定某个加载器放到队列的最前面以确保它最先被调用。Yii的类自动加载机制就是基于spl_autoload_register()方法的。

Yii的类自动加载机制要从它的入口文件index.php说起了,该文件源码如下:

<?php
defined(&#39;YII_DEBUG&#39;) or define(&#39;YII_DEBUG&#39;, true);//运行模式
defined(&#39;YII_ENV&#39;) or define(&#39;YII_ENV&#39;, &#39;dev&#39;);//运行环境
require(__DIR__ . &#39;/../../vendor/autoload.php&#39;);//composer的类自动加载文件
require(__DIR__ . &#39;/../../vendor/yiisoft/yii2/Yii.php&#39;);//yii的工具类文件(包含了yii类自动加载)
require(__DIR__ . &#39;/../../common/config/bootstrap.php&#39;);//主要用于执行一些yii应用引导的代码
require(__DIR__ . &#39;/../config/bootstrap.php&#39;);
$config = yii\helpers\ArrayHelper::merge(
  require(__DIR__ . &#39;/../../common/config/main.php&#39;),
  require(__DIR__ . &#39;/../../common/config/main-local.php&#39;),
  require(__DIR__ . &#39;/../config/main.php&#39;),
  require(__DIR__ . &#39;/../config/main-local.php&#39;)
);
(new yii\web\Application($config))->run();
Copy after login

文件中第4、5行代码分别引入了composer的类自动加载文件和yii的工具类文件Yii.php,Yii.php文件源码如下:

require(__DIR__ . &#39;/BaseYii.php&#39;);
class Yii extends \yii\BaseYii
{
}
spl_autoload_register([&#39;Yii&#39;, &#39;autoload&#39;], true, true);//注册yii的类自动加载器
Yii::$classMap = require(__DIR__ . &#39;/classes.php&#39;);//引入类名到类文件路径的映射
Yii::$container = new yii\di\Container();
Copy after login

这个文件定义了Yii类继承自\yii\BaseYii,代码的第6行引入了classes.php文件,该文件源码:

return [
 &#39;yii\base\Action&#39; => YII2_PATH . &#39;/base/Action.php&#39;,
 &#39;yii\base\ActionEvent&#39; => YII2_PATH . &#39;/base/ActionEvent.php&#39;,
  ....//省略n多元素
 &#39;yii\widgets\Pjax&#39; => YII2_PATH . &#39;/widgets/Pjax.php&#39;,
 &#39;yii\widgets\PjaxAsset&#39; => YII2_PATH . &#39;/widgets/PjaxAsset.php&#39;,
 &#39;yii\widgets\Spaceless&#39; => YII2_PATH . &#39;/widgets/Spaceless.php&#39;,
];
Copy after login

通过查看其源码可以看到,这个文件返回了一个从类名称到类文件路径的映射数组。这个数组被赋值给Yii::$classMap。代码的第7行调用了spl_autoload_register()方法注册了一个类自动加载器,这个类加载器为Yii::autoload(),这就是yii的类加载器了。同时这里通过把spl_autoload_register()方法第三个参数赋值为true,把yii的类加载器放在了加载器队列的最前面,所以当访问一个未加载的类的时候,yii的类自动加载器会最先被调用。

下面我们就来看看yii的类自动加载器Yii::autoload()到底做了些什么,这个方法实际上在yii\BaseYii类中,源码如下:

/**
 * 类自动加载器
 * @param type $className:要加载的类的名称
 * @return type
 * @throws UnknownClassException
 */
public static function autoload($className)
{
  if (isset(static::$classMap[$className])) {//要加载的类在 类名=>类文件路径 映射中找到
    $classFile = static::$classMap[$className];
    if ($classFile[0] === &#39;@&#39;) {//若类文件路径使用了别名,进行别名解析获得完整路径
      $classFile = static::getAlias($classFile);
    }
  } elseif (strpos($className, &#39;\\&#39;) !== false) {//类名需要包含&#39;\&#39;才符合规范
    $classFile = static::getAlias(&#39;@&#39; . str_replace(&#39;\\&#39;, &#39;/&#39;, $className) . &#39;.php&#39;, false);//进行别名解析(说明类名必须以有效的根别名打头)
    if ($classFile === false || !is_file($classFile)) {
      return;
    }
  } else {
    return;
  }
  include($classFile);//引入需要加载的类文件
  if (YII_DEBUG && !class_exists($className, false) && !interface_exists($className, false) && !trait_exists($className, false)) {
    throw new UnknownClassException("Unable to find &#39;$className&#39; in file: $classFile. Namespace missing?");
  }
}
Copy after login

这个方法首先会根据需要加载的类的名称去Yii::$classMap这个映射数组中查找,若存在则引入对应的类文件,不存在则进行别名解析得到完整文件路径,这里也说明若使用的类不在YII::$classMap中事先定义,则类名必须以有效的根别名打头,否则无法找到对应文件。

就这样,在yii中无需在程序中事先加载一大堆可能会使用到的类文件,当使用到某个类的时候,yii的类自动加载器就会自动进行加载了,高效又便捷!

相关推荐:

crontab中如何调用yii框架类中的一个方法

The above is the detailed content of Yii2 framework class automatic loading mechanism example analysis. For more information, please follow other related articles on the PHP Chinese website!

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

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Roblox: Bubble Gum Simulator Infinity - How To Get And Use Royal Keys
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Nordhold: Fusion System, Explained
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)

Hot Topics

Java Tutorial
1664
14
PHP Tutorial
1269
29
C# Tutorial
1248
24
Error loading plugin in Illustrator [Fixed] Error loading plugin in Illustrator [Fixed] Feb 19, 2024 pm 12:00 PM

When launching Adobe Illustrator, does a message about an error loading the plug-in pop up? Some Illustrator users have encountered this error when opening the application. The message is followed by a list of problematic plugins. This error message indicates that there is a problem with the installed plug-in, but it may also be caused by other reasons such as a damaged Visual C++ DLL file or a damaged preference file. If you encounter this error, we will guide you in this article to fix the problem, so continue reading below. Error loading plug-in in Illustrator If you receive an "Error loading plug-in" error message when trying to launch Adobe Illustrator, you can use the following: As an administrator

Stremio subtitles not working; error loading subtitles Stremio subtitles not working; error loading subtitles Feb 24, 2024 am 09:50 AM

Subtitles not working on Stremio on your Windows PC? Some Stremio users reported that subtitles were not displayed in the videos. Many users reported encountering an error message that said "Error loading subtitles." Here is the full error message that appears with this error: An error occurred while loading subtitles Failed to load subtitles: This could be a problem with the plugin you are using or your network. As the error message says, it could be your internet connection that is causing the error. So please check your network connection and make sure your internet is working properly. Apart from this, there could be other reasons behind this error, including conflicting subtitles add-on, unsupported subtitles for specific video content, and outdated Stremio app. like

PHP implements infinite scroll loading PHP implements infinite scroll loading Jun 22, 2023 am 08:30 AM

With the development of the Internet, more and more web pages need to support scrolling loading, and infinite scrolling loading is one of them. It allows the page to continuously load new content, allowing users to browse the web more smoothly. In this article, we will introduce how to implement infinite scroll loading using PHP. 1. What is infinite scroll loading? Infinite scroll loading is a method of loading web content based on scroll bars. Its principle is that when the user scrolls to the bottom of the page, background data is asynchronously retrieved through AJAX to continuously load new content. This kind of loading method

How to solve the problem that css cannot be loaded How to solve the problem that css cannot be loaded Oct 20, 2023 am 11:29 AM

The solutions to the problem that CSS cannot be loaded include checking the file path, checking the file content, clearing the browser cache, checking the server settings, using developer tools and checking the network connection. Detailed introduction: 1. Check the file path. First, please make sure the path of the CSS file is correct. If the CSS file is located in a different part or subdirectory of the website, you need to provide the correct path. If the CSS file is located in the root directory, the path should be direct. ; 2. Check the file content. If the path is correct, the problem may lie in the CSS file itself. Open the CSS file to check, etc.

Outlook freezes when inserting hyperlink Outlook freezes when inserting hyperlink Feb 19, 2024 pm 03:00 PM

If you encounter freezing issues when inserting hyperlinks into Outlook, it may be due to unstable network connections, old Outlook versions, interference from antivirus software, or add-in conflicts. These factors may cause Outlook to fail to handle hyperlink operations properly. Fix Outlook freezes when inserting hyperlinks Use the following fixes to fix Outlook freezes when inserting hyperlinks: Check installed add-ins Update Outlook Temporarily disable your antivirus software and then try creating a new user profile Fix Office apps Program Uninstall and reinstall Office Let’s get started. 1] Check the installed add-ins. It may be that an add-in installed in Outlook is causing the problem.

How to remove jquery in yii2 How to remove jquery in yii2 Feb 17, 2023 am 09:55 AM

How to remove jquery from yii2: 1. Edit the AppAsset.php file and comment out the "yii\web\YiiAsset" value in the variable $depends; 2. Edit the main.php file and add the configuration "'yii" under the field "components" \web\JqueryAsset' => ['js' => [],'sourcePath' => null,]," to remove the jquery script.

What should I do if Windows 7 fails to load the USB driver? What should I do if Windows 7 fails to load the USB driver? Jul 11, 2023 am 08:13 AM

When installing the win7 system, some netizens encountered a situation where loading the USB driver failed. The USB device could not be recognized in the new win7 system, and common USB flash drives, mice and other devices could not be used. So what should I do if the installation of win7 fails to load the USB driver? Let Xiaobai teach you how to solve the problem of failure to load the USB driver when installing win7. Method 1: 1. First, we turn on the computer and enter the computer system, and check the computer system version in the computer system. Confirm whether the version of the computer system is consistent with the version of the device driver. 2. After confirming the driver version, connect the USB device to the computer system. The computer system shows that the device cannot connect to the system. 3. On the connection information page, click the Help button to view the help information. 4. If the computer department

Deep understanding of the mechanics of CSS layout recalculation and rendering Deep understanding of the mechanics of CSS layout recalculation and rendering Jan 26, 2024 am 09:11 AM

CSS reflow and repaint are very important concepts in web page performance optimization. When developing web pages, understanding how these two concepts work can help us improve the response speed and user experience of the web page. This article will delve into the mechanics of CSS reflow and repaint, and provide specific code examples. 1. What is CSS reflow? When the visibility, size or position of elements in the DOM structure changes, the browser needs to recalculate and apply CSS styles and then re-layout

See all articles