php mvc init自动执行,MVC之路---php自动载入

本文主要利用__autoload,spl_autoload_register,spl_autoload实现类的自动载入以及命名空间的理解

项目开发中我们难免要加载各种各样的类,如果我们需要一个类,就require一个文件,这样子效率非常低效。,当然,这种类的加载如果用到框架的话,框架的底层已经实现,我们只需要关心业务逻辑即可

一 __autoload 魔法函数

在PHP5.1之前,没有spl_autoload_register函数,我们会用php自带的魔法函数__autoload()实现自动加载,

先看目录结构

4172f8c10a41?from=singlemessage

image.png

db目录下有存放类A的php文件。存放类B的php文件.按正常的逻辑我们是要把这两个文件都require进来,不然会直接报错

类A内容

4172f8c10a41?from=singlemessage

image.png

类B内容

4172f8c10a41?from=singlemessage

image.png

index.php文件内容

4172f8c10a41?from=singlemessage

image.png

效果

4172f8c10a41?from=singlemessage

image.png

但如果我们有类C,类DEFG......这样子我们是不是要一个个require进来呢,这样子效率极其低效。我们稍微改进下,使用__autoload函数自动载入

上代码

function __autoload($className){

require_once '/db/'.$className.'.php';

}

效果如下

4172f8c10a41?from=singlemessage

image.png

这时候就不需要再多次require_once类A B C D E F G,很方便,因为类被实例化的时候就会先检测当前已载入的文件是否存在这个类,不存在则自动把类名作为参数 传入到__autoload()函数,然后我们在__autoload函数接收类名。再根据类名以及目录关系载入php文件。但是__autoload函数有个鸡肋的地方,就是一个应用中只允许有一个__autolaod函数 那假如我们有很多个目录,除了db,我们还有model,route等等等目录的时候就比较麻烦了,而且高版本的php已经不建议__autoload函数,那么如果我们想实现多目录,复杂的文件载入的话,使用什么比较好呢,推荐使用spl_autoload_register

spl_autoload_register

autoload文件代码改为

spl_autoload_register('loadDb');

spl_autoload_register('loadHelp');

function loadDb($className){

$file = str_replace('\\','/',dirname(__File__)).'/db/'.$className.'.php';

if(file_exists($file)){

require_once './db/'.$className.'.php';

}

}

function loadHelp($className){

$file = str_replace('\\','/',dirname(__File__)).'/helper/'.$className.'.php';

if(file_exists($file)){

require_once './helper/'.$className.'.php';

}

}

看效果

4172f8c10a41?from=singlemessage

image.png

使用sql_autoload函数即可实现不同目录的文件进行自动载入,但是为了避免全局函数污染,autoload可以改进下

class AutoLoad{

//根目录路径

private $dir;

//保存AutoLoad,防止重复调用本类

private static $loader = NULL;

//启动自动载入

public static function init(){

self::$loader == NULL && self::$loader = new self ();

return self::$loader;

}

//初始化即注册自动载入

public function __construct(){

$this->dir = str_replace('\\','/',dirname(__File__));

spl_autoload_register([$this,'loadDb']);

spl_autoload_register([$this,'loadHelp']);

}

//加载db文件夹下php文件

private function loadDb($className){

$file = $this->dir.'/db/'.$className.'.php';

file_exists($file) && require_once $file;

}

//加载helper文件夹php文件

private function loadHelp($className){

$file = $this->dir.'/helper/'.$className.'.php';

file_exists($file) && require_once $file;

}

}

AutoLoad::init();

改进后看效果,加了点测试代码

4172f8c10a41?from=singlemessage

image.png

到此,php自动载入分享完毕,如果想了解更多的spl_autoload家族可以查阅相关文献或留言本人

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值