/
ClassLoader.php
84 lines (76 loc) · 2.23 KB
/
ClassLoader.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
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
<?php
namespace Symfony\Foundation;
/*
* This file is part of the symfony package.
*
* (c) Fabien Potencier <fabien.potencier@symfony-project.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
/**
* ClassLoader implementation that implements the technical interoperability
* standards for PHP 5.3 namespaces and class names.
*
* Based on http://groups.google.com/group/php-standards/web/psr-0-final-proposal
*
* Example usage:
*
* [php]
* $loader = new ClassLoader();
* $loader->registerNamespace('Symfony', __DIR__.'/..');
* $loader->register();
*
* @author Jonathan H. Wage <jonwage@gmail.com>
* @author Roman S. Borschel <roman@code-factory.org>
* @author Matthew Weier O'Phinney <matthew@zend.com>
* @author Kris Wallsmith <kris.wallsmith@gmail.com>
* @author Fabien Potencier <fabien.potencier@symfony-project.org>
*/
class ClassLoader
{
protected $namespaces = array();
/**
* Creates a new loader for classes of the specified namespace.
*
* @param string $namespace The namespace to use
* @param string $includePath The path to the namespace
*/
public function registerNamespace($namespace, $includePath = null)
{
$this->namespaces[$namespace] = $includePath;
}
/**
* Installs this class loader on the SPL autoload stack.
*/
public function register()
{
spl_autoload_register(array($this, 'loadClass'));
}
/**
* Loads the given class or interface.
*
* @param string $className The name of the class to load
*/
public function loadClass($className)
{
$vendor = substr($className, 0, stripos($className, '\\'));
if (!isset($this->namespaces[$vendor]))
{
return;
}
if (false !== ($lastNsPos = strripos($className, '\\')))
{
$namespace = substr($className, 0, $lastNsPos);
$className = substr($className, $lastNsPos + 1);
$fileName = str_replace('\\', DIRECTORY_SEPARATOR, $namespace).DIRECTORY_SEPARATOR;
}
else
{
$namespace = '';
$fileName = '';
}
$fileName .= str_replace('_', DIRECTORY_SEPARATOR, $className).'.php';
require $this->namespaces[$vendor].DIRECTORY_SEPARATOR.$fileName;
}
}