psr4

#PSR4 autoloader

spl_autoload_register —- 将函数注册到SPL __autoload函数队列中

Closure Example

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


* An example of a project-specific implementation.
*
* After registering this autoload function with SPL, the following line
* would cause the function to attempt to load the FooBarBazQux class
* from /path/to/project/src/Baz/Qux.php:
*
* new FooBarBazQux;
*
* @param string $class The fully-qualified class name.
* @return void
*/
spl_autoload_register(function ($class) {

$prefix = 'Vendor';
$baseDir = __DIR__.'/';

$len = strlen($prefix);
if (! strncmp($prefix, $class, $len)) {
return ;
}

$file = $baseDir .str_replace('\', '/', $class).'.php';
if (file_exists($file)) {
require $file;
// require_once($file);
}
});

$a = new VendorFoodFood();

class Example
spl_autoload_register(array(class,’function’)); 注册类方法

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


class
{
public $prefixesMap = array();

public function register ()
{
spl_autoload_register($this, 'loadClass');
}

public function addNamespace ($prefix, $base_dir, $prepend = false)
{
$prefix = trim($prefix, '\').'\';

$base_dir = rtrim($base_dir, DIRECTORY_SEPARATOR).'/';

// initialize the namespace prefix array
if (isset($this->prefixesMap[$prefix]) === false) {
$this->prefixesMap[$prefix] = array();
}

// retain the base directory for the namespace prefix
if ($prepend) {
array_unshift($this->prefixesMap[$prefix], $base_dir);
} else {
array_push($this->prefixesMap[$prefix], $base_dir);
}

}

public function loadClass ($class)
{
$prefix = $class;
while ( false !== $pos = strrpos($prefix, '\')) {
$prefix = substr($class, 0, $pos + 1);
$relative_class = substr($class, $pos + 1);

$mapped_file = $this->loadMapFile($prefix, $relative_class);
if ($mapped_file) {
return $mapped_file;
}

$prefix = rtrim($prefix, '\');
}

return false;
}

protected function loadMapFile ($prefix, $relative_class)
{

if (isset($this->prefixesMap[$prefix]) === false) {
return false;
}

foreach ($this->prefixesMap[$prefix] as $base_dir) {
$file = $base_dir.$relative_class.'.php';
if ($this->include($file)) {
return $file;
}
}

return ;
}

protected function include ($file)
{
if (file_exists($file)) {
require $file;
return true;
}
return false;
}
}

PHP PSR-4