loader.php 1.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950
  1. <?php
  2. //http://www.leaseweblabs.com/2014/04/psr-0-psr-4-autoloading-classes-php/
  3. class Loader
  4. {
  5. protected static $parentPath = null;
  6. protected static $paths = null;
  7. protected static $files = null;
  8. protected static $nsChar = '\\';
  9. protected static $initialized = false;
  10. protected static function initialize()
  11. {
  12. if (static::$initialized) return;
  13. static::$initialized = true;
  14. static::$parentPath = __FILE__;
  15. for ($i=substr_count(get_class(), static::$nsChar);$i>=0;$i--) {
  16. static::$parentPath = dirname(static::$parentPath);
  17. }
  18. static::$paths = array();
  19. static::$files = array(__FILE__);
  20. }
  21. public static function register($path,$namespace) {
  22. if (!static::$initialized) static::initialize();
  23. static::$paths[$namespace] = trim($path,DIRECTORY_SEPARATOR);
  24. }
  25. public static function load($class) {
  26. if (class_exists($class,false)) return;
  27. if (!static::$initialized) static::initialize();
  28. foreach (static::$paths as $namespace => $path) {
  29. if (!$namespace || $namespace.static::$nsChar === substr($class, 0, strlen($namespace.static::$nsChar))) {
  30. $fileName = substr($class,strlen($namespace.static::$nsChar)-1);
  31. $fileName = str_replace(static::$nsChar, DIRECTORY_SEPARATOR, ltrim($fileName,static::$nsChar));
  32. $fileName = static::$parentPath.DIRECTORY_SEPARATOR.$path.DIRECTORY_SEPARATOR.$fileName.'.php';
  33. if (file_exists($fileName)) {
  34. include $fileName;
  35. return true;
  36. }
  37. }
  38. }
  39. return false;
  40. }
  41. }
  42. spl_autoload_register(array('Loader', 'load'));