如何实现一个php框架系列文章【3】支持psr4的自动加载类

psr4自动加载规范 https://github.com/PizzaLiu/PHP-FIG/blob/master/PSR-4-autoloader-cn.md

我们把第三方使用psr规范的类库放在vendor目录下

修改一下autoload函数

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
    //psr
    if (!empty($GLOBALS['_UCT']['autoload_psr'])) {
        //namespace
        if(false !== strpos($class_name'\')) {
            $dir str_replace('\', DS, ltrim($class_name'\')).'.php';
        }
        else {
            $dir str_replace('_', DS, $class_name).'.php';
        }
 
        foreach ($GLOBALS['_UCT']['autoload_psr'as $vendor) {
            if(!strncmp($vendor.DS, $dirstrlen($vendor) + 1)) {
                $f = UCT_PATH . 'vendor' . DS . $dir;
            }
            else {
                $f = UCT_PATH . 'vendor' . DS . $vendor . DS . $dir;
            }
            if (file_exists($f)) {
                return include $f;
            }
        }
    }

 

引用第三方类库

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
function uct_use_vendor($vendor) {
    if (empty($GLOBALS['_UCT']['autoload_psr'])) {
        $GLOBALS['_UCT']['autoload_psr'] = array(
            $vendor
        );
        return true;
    }
    if (!in_array($vendor$GLOBALS['_UCT']['autoload_psr'])) {
        //$GLOBALS['_UCT']['autoload_psr'][] = $app;    
        array_unshift($GLOBALS['_UCT']['autoload_psr'], $vendor);
        return true;
    }
 
    return false;
}
原文地址:https://www.cnblogs.com/yyluming/p/5171099.html