Commit | Line | Data |
---|---|---|
14d4f286 S |
1 | <?php |
2 | /** | |
3 | * An implementation of the PSR-0 Autoloader. This can be replaced at will with | |
4 | * other implementations if necessary. | |
5 | * | |
6 | * PHP version 5.3 | |
7 | * | |
8 | * @category PHPCryptLib | |
9 | * @package Core | |
10 | * @author Anthony Ferrara <ircmaxell@ircmaxell.com> | |
11 | * @copyright 2011 The Authors | |
12 | * @license http://www.opensource.org/licenses/mit-license.html MIT License | |
13 | * @version Build @@version@@ | |
14 | */ | |
15 | ||
16 | namespace CryptLib\Core; | |
17 | ||
18 | /** | |
19 | * An implementation of the PSR-0 Autoloader. This can be replaced at will with | |
20 | * other implementations if necessary. | |
21 | * | |
22 | * @category PHPCryptLib | |
23 | * @package Core | |
24 | * @author Anthony Ferrara <ircmaxell@ircmaxell.com> | |
25 | */ | |
26 | class AutoLoader { | |
27 | ||
28 | /** | |
29 | * @var string The namespace prefix for this instance. | |
30 | */ | |
31 | protected $namespace = ''; | |
32 | ||
33 | /** | |
34 | * @var string The filesystem prefix to use for this instance | |
35 | */ | |
36 | protected $path = ''; | |
37 | ||
38 | /** | |
39 | * Build the instance of the autoloader | |
40 | * | |
41 | * @param string $namespace The prefixed namespace this instance will load | |
42 | * @param string $path The filesystem path to the root of the namespace | |
43 | * | |
44 | * @return void | |
45 | */ | |
46 | public function __construct($namespace, $path) { | |
47 | $this->namespace = ltrim($namespace, '\\'); | |
48 | $this->path = rtrim($path, '/\\') . DIRECTORY_SEPARATOR; | |
49 | } | |
50 | ||
51 | /** | |
52 | * Try to load a class | |
53 | * | |
54 | * @param string $class The class name to load | |
55 | * | |
56 | * @return boolean If the loading was successful | |
57 | */ | |
58 | public function load($class) { | |
59 | $class = ltrim($class, '\\'); | |
60 | if (strpos($class, $this->namespace) === 0) { | |
61 | $nsparts = explode('\\', $class); | |
62 | $class = array_pop($nsparts); | |
63 | $nsparts[] = ''; | |
64 | $path = $this->path . implode(DIRECTORY_SEPARATOR, $nsparts); | |
65 | $path .= str_replace('_', DIRECTORY_SEPARATOR, $class) . '.php'; | |
66 | if (file_exists($path)) { | |
67 | require $path; | |
68 | return true; | |
69 | } | |
70 | } | |
71 | return false; | |
72 | } | |
73 | ||
74 | /** | |
75 | * Register the autoloader to PHP | |
76 | * | |
77 | * @return boolean The status of the registration | |
78 | */ | |
79 | public function register() { | |
80 | return spl_autoload_register(array($this, 'load')); | |
81 | } | |
82 | ||
83 | /** | |
84 | * Unregister the autoloader to PHP | |
85 | * | |
86 | * @return boolean The status of the unregistration | |
87 | */ | |
88 | public function unregister() { | |
89 | return spl_autoload_unregister(array($this, 'load')); | |
90 | } | |
91 | ||
92 | } |