-
Notifications
You must be signed in to change notification settings - Fork 1
/
DynamicAutoloader.php
67 lines (59 loc) · 1.5 KB
/
DynamicAutoloader.php
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
<?php
/**
* Dynamic autoloader.
*
* This autoloader searches for a class inside a bunch of paths and includes the class if exists.
* Please note that the class name should be the same as PHP file name.
*
* @author Ahmad Mayahi <[email protected]>
* @license MIT
* @version 1.0
*/
class DynamicAutoloader
{
private $paths;
/**
* DynamicAutoloader constructor.
*
* @param $paths it can be either a string with PATH_SEPARATOR or an array of paths.
* @throws Exception
*/
public function __construct($paths)
{
if ('' == $paths) {
throw new Exception('Please set the paths.');
}
$this->paths = $paths;
spl_autoload_register(array($this, 'autoload'));
}
/**
* Get the paths.
*
* @return array
*/
private function getPaths()
{
if (!is_array($this->paths)) {
return explode(PATH_SEPARATOR, $this->paths);
}
return $this->paths;
}
/**
* Autoloader.
*
* @param $class
* @throws Exception
*/
private function autoload($class)
{
$classFile = str_replace('\\', DIRECTORY_SEPARATOR, $class) . '.php';
foreach ($this->getPaths() as $path) {
$file = $path . DIRECTORY_SEPARATOR . $classFile;
if (file_exists($file)) {
require_once $file;
return;
}
}
throw new Exception($class . ' Cannot be found!');
}
}