1: <?php
2: /**
3: * Horde_Autoloader
4: *
5: * Manages an application's class name to file name mapping conventions. One or
6: * more class-to-filename mappers are defined, and are searched in LIFO order.
7: *
8: * @author Bob Mckee <bmckee@bywires.com>
9: * @author Chuck Hagenbuch <chuck@horde.org>
10: * @category Horde
11: * @package Autoloader
12: */
13: class Horde_Autoloader
14: {
15: private $_mappers = array();
16: private $_callbacks = array();
17:
18: public function loadClass($className)
19: {
20: if ($path = $this->mapToPath($className)) {
21: if ($this->_include($path)) {
22: $className = strtolower($className);
23: if (isset($this->_callbacks[$className])) {
24: call_user_func($this->_callbacks[$className]);
25: }
26: return true;
27: }
28: }
29:
30: return false;
31: }
32:
33: public function addClassPathMapper(Horde_Autoloader_ClassPathMapper $mapper)
34: {
35: array_unshift($this->_mappers, $mapper);
36: return $this;
37: }
38:
39: /**
40: * Add a callback to run when a class is loaded through loadClass().
41: *
42: * @param string $class The classname.
43: * @param mixed $callback The callback to run when the class is loaded.
44: */
45: public function addCallback($class, $callback)
46: {
47: $this->_callbacks[strtolower($class)] = $callback;
48: }
49:
50: public function registerAutoloader()
51: {
52: // Register the autoloader in a way to play well with as many
53: // configurations as possible.
54: spl_autoload_register(array($this, 'loadClass'));
55: if (function_exists('__autoload')) {
56: spl_autoload_register('__autoload');
57: }
58: }
59:
60: /**
61: * Search registered mappers in LIFO order.
62: */
63: public function mapToPath($className)
64: {
65: foreach ($this->_mappers as $mapper) {
66: if ($path = $mapper->mapToPath($className)) {
67: if ($this->_fileExists($path)) {
68: return $path;
69: }
70: }
71: }
72: }
73:
74: protected function _include($path)
75: {
76: return (bool)include $path;
77: }
78:
79: protected function _fileExists($path)
80: {
81: return file_exists($path);
82: }
83: }
84: