您的位置:首页 > 编程语言 > PHP开发

[PHP] 类的自动加载和在命名空间中实现

2019-02-24 19:54 246 查看

说明:

在我们加载PHP文件时候,不希望 include 或者 require 引入太多的函数,或者选择性加载其中一些文件的时候会很麻烦.所以才有了自动加载这个机制.

__autoload():

[code]__autoload ( string $class ) : void

class
待加载的类名。

在PHP中这是一个魔术函数.通常在PHP中需要实例化(new)一个类,但是当这个类并没有被定义的时候,__autoload() 就会被触发.如果在 __autoload() 函数中引入该类的PHP文件的时候,该实例化则会成功(在PHP7中已经不建议使用该函数,而改用spl_autoload_register来实现).

spl_autoload_register():

[code]spl_autoload_register ([ callable $autoload_function [, bool $throw = true [, bool $prepend = false ]]] ) : bool

autoload_function
欲注册的自动装载函数。如果没有提供任何参数,则自动注册 autoload 的默认实现函数spl_autoload()。

throw
此参数设置了 autoload_function 无法成功注册时, spl_autoload_register()是否抛出异常。

prepend
如果是 true,spl_autoload_register() 会添加函数到队列之首,而不是队列尾部。

PHP推荐使用该函数来定义自动加载,原因是PHP中不允许函数重名,所以 __autoload() 函数只能定义一次,进而导致了它的鸡肋性.而PHP官方推出的 spl_autoload_register() 函数没有这方面的限制,甚至当 __autoload() 和 spl_autoload_register() 同时存在时以 spl_autoload_register() 为准(官方这么强推,让之前的__autoload()函数怎么活啊).

命名空间:

在很多框架中我们并没有使用 spl_autoload_register()函数,但是调用的类依然可以使用,这是因为在PHP5.3版本后可以将命名空间也引入的概念.

在我们平常使用命名空间只是让类名有了前缀,不容易产生冲突,但是系统仍然不会在我们 use 时进行自动加载.这个时候就需要 __autoload() 和 spl_autoload_register() 来加载类,否则就会报错.

[code]//index.php

spl_autoload_register(function ($class){
//从我们的 class名称中找,有没有对应的路径
$map = [
'top\\Test'=>'./Test.php'
];

$file = $map[$class];
//查看对应的文件是否存在
if (file_exists($file))
include $file;
});

new top\School();

在上面通过搭建类名和地址的映射关系,实现了自动加载.但是这样会导致需要不断的修改添加新的映射关系来维持,所以需要 PSR4 自动加载规范 来维持这样的映射关系.

PSR4 自动加载规范:

PSR4 中文文档

PSR-4 是关于由文件路径自动载入对应类的相关规范,规范规定了一个完全限定类名需要具有以下结构:

[code]\<NamespaceName>(\<SubNamespaceNames>)*\<ClassName>

PSR-4 规范中必须要有一个顶级命名空间,它的意义在于表示某一个特殊的目录(文件基目录)。子命名空间代表的是类文件相对于文件基目录的这一段路径(相对路径),类名则与文件名保持一致(注意大小写的区别)。

举个例子:在全限定类名 \app\view\news\Index 中,如果 app 代表 C:\Baidu,那么这个类的路径则是 C:\Baidu\view\news\Index.php

我们就以解析 \app\view\news\Index 为例,编写一个简单的 Demo:

[code]$class = 'app\view\news\Index';

/* 顶级命名空间路径映射 */
$vendor_map = array(
'app' => 'C:\Baidu',
);

/* 解析类名为文件路径 */
$vendor = substr($class, 0, strpos($class, '\\')); // 取出顶级命名空间[app]
$vendor_dir = $vendor_map[$vendor]; // 文件基目录[C:\Baidu]
$rel_path = dirname(substr($class, strlen($vendor))); // 相对路径[/view/news]
$file_name = basename($class) . '.php'; // 文件名[Index.php]

/* 输出文件所在路径 */
echo $vendor_dir . $rel_path . DIRECTORY_SEPARATOR . $file_name;

通过这个 Demo 可以看出限定类名转换为路径的过程。那么现在就让我们用规范的面向对象方式去实现自动加载器吧。

首先我们创建一个文件 Index.php,它处于 \app\mvc\view\home 目录中:

[code]namespace app\mvc\view\home;

class Index
{
function __construct()
{
echo '<h1> Welcome To Home </h1>';
}
}

接着我们在创建一个加载类(不需要命名空间),它处于 \ 目录中:

[code]class Loader
{
/* 路径映射 */
public static $vendorMap = array(
'app' => __DIR__ . DIRECTORY_SEPARATOR . 'app',
);

/**
* 自动加载器
*/
public static function autoload($class)
{
$file = self::findFile($class);
if (file_exists($file)) {
self::includeFile($file);
}
}

/**
* 解析文件路径
*/
private static function findFile($class)
{
$vendor = substr($class, 0, strpos($class, '\\')); // 顶级命名空间
$vendorDir = self::$vendorMap[$vendor]; // 文件基目录
$filePath = substr($class, strlen($vendor)) . '.php'; // 文件相对路径
return strtr($vendorDir . $filePath, '\\', DIRECTORY_SEPARATOR); // 文件标准路径
}

/**
* 引入文件
*/
private static function includeFile($file)
{
if (is_file($file)) {
include $file;
}
}
}

最后,将 Loader 类中的 autoload 注册到 spl_autoload_register 函数中:

[code]include 'Loader.php'; // 引入加载器
spl_autoload_register('Loader::autoload'); // 注册自动加载

new \app\mvc\view\home\Index(); // 实例化未引用的类

/**
* 输出: <h1> Welcome To Home </h1>
*/

示例中的代码其实就是 ThinkPHP 自动加载器源码的精简版,它是 ThinkPHP 5 能实现惰性加载的关键。

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: