-
Notifications
You must be signed in to change notification settings - Fork 7
Expand file tree
/
Copy pathAutoloader.php
More file actions
95 lines (83 loc) · 1.53 KB
/
Autoloader.php
File metadata and controls
95 lines (83 loc) · 1.53 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
<?php
/**
* Autoloader(命名空间,自动加载类)
*
* @author Chen Peng(forward.nice.cp@gmail.com)
*/
namespace Bootstrap;
class Autoloader {
// 站点根目录,可配置多个子目录
protected $domainRoot = array();
public function __construct()
{
$this->domainRoot = array(
// 默认目录上层两级目录为根目录
__DIR__ . '/../../',
__DIR__ . '/../',
);
}
/**
* 清空当前web目录
*
* @return object
*/
public function clear()
{
$this->domainRoot = array();
return $this;
}
/**
* 返回当前实例
*
* @return object
*/
public static function instance()
{
return new static;
}
/**
* 设置web目录
*
* @param sting $root
* @return object
*/
public function setRoot($root = '')
{
if (!$root || !is_dir(realpath($root))) {
throw new \Exception('No root param exposed or invalid path');
}
$this->domainRoot[] = realpath($root);
return $this;
}
/**
* Autoloader 核心方法,加载对应文件
*
* @param string $class
* @return bool
*/
protected function autoloader($class)
{
$file = str_replace('\\', DIRECTORY_SEPARATOR, $class) . '.php';
foreach ($this->domainRoot as $path) {
clearstatcache();
$path = $path . DIRECTORY_SEPARATOR . $file;
if (is_file($path)) {
require_once $path;
if (class_exists($class, false)) {
return true;
}
}
}
return false;
}
/**
* 初始化
*
* @return object
*/
public function init()
{
spl_autoload_register(array($this, 'autoloader'));
return $this;
}
}