[PHP] 项目实践中的自动加载实现

2022-10-22,,,

1.使用spl_autoload_register函数注册一个自己定义的自动加载函数
2.当在代码中new一个不存在的类的时候,上面的函数会被调用,不存在的类名会被作为参数传入该函数中
3.兼容了两种方式,命名空间对应目录的方式 \app\test,类名下划线分割对应目录的方式app_test,都是对应的app目录下的test.php文件,类名要和文件名一致
4.set_include_path(),可以有多个用冒号:隔开,动态设置php.ini中的include_path 配置选项

 

<?php
class application {
    private static $instance    = null;
    private $libpath            = './';
    private $phpext             = '.php';
    public function setlibpath($path, $autoload = false) {
        $this->libpath = trim(trim($path), directory_separator);
        set_include_path($this->getlibpath());
        if ($autoload) {
            spl_autoload_register(array('application', 'load'));
        }
        return $this;
    }
    public static function instance() {
        if (!self::$instance) {
            self::$instance = new self();
        }
        return self::$instance;
    }
    //获取文件后缀
    public function getphpext() {
        return $this->phpext;
    }
    //设置文件后缀
    public function setphpext($ext) {
        $this->phpext = $ext;
        return $this;
    }
    //设置根路径
    public function setpath($path) {
        $this->path = rtrim(trim($path), directory_separator);
        return $this;
    }
    //设置自动加载的路径
    public function getlibpath() {
        return $this->path . directory_separator . $this->libpath;
    }
    //自动加载函数
    public static function load($class) {
        $pos = strrpos($class, '\\');
        if ($pos !== false) {
            $ns = str_replace('\\', directory_separator, substr($class, 0, $pos + 1));
            $classname = substr($class, $pos + 1);
        } else {
            $ns = directory_separator;
            $classname = $class;
        }
        if (strpos($classname, '_') !== false) {
            $classname = str_replace('_', directory_separator, $classname);
        }        
        $ins = self::instance();
        $classfile = $ins->getlibpath() . $ns . $classname . $ins->getphpext();
        if (!(include $classfile)) {
            throw new exception('load class failed: class=' . $class . ' file=' . $classfile);
        }
    }
}
application::instance()->setpath(dirname(__file__))->setlibpath(directory_separator, true);
//测试,在根目录创建app目录,下面创建这两个文件
new app_user();
new \app\admin();

app目录下面的user.php

<?php
class app_user{
    public function __construct(){
        new \app\admin();
    }
}

app目录下的admin.php

<?php
namespace app;
class admin{}

 

《[PHP] 项目实践中的自动加载实现.doc》

下载本文的Word格式文档,以方便收藏与打印。