loader.php 1.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869
  1. <?php
  2. //http://www.leaseweblabs.com/2014/04/psr-0-psr-4-autoloading-classes-php/
  3. class Loader {
  4. protected static $parentPath = null;
  5. protected static $paths = null;
  6. protected static $files = null;
  7. protected static $nsChar = "\\";
  8. protected static $initialized = false;
  9. protected static function initialize() {
  10. if (static::$initialized) {
  11. return;
  12. }
  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 = [];
  19. static::$files = [__FILE__];
  20. }
  21. public static function register($path, $namespace) {
  22. if (!static::$initialized) {
  23. static::initialize();
  24. }
  25. static::$paths[$namespace] = trim($path, DIRECTORY_SEPARATOR);
  26. }
  27. public static function load($class) {
  28. if (class_exists($class, false)) {
  29. return;
  30. }
  31. if (!static::$initialized) {
  32. static::initialize();
  33. }
  34. foreach (static::$paths as $namespace => $path) {
  35. if (
  36. !$namespace ||
  37. $namespace . static::$nsChar ===
  38. substr($class, 0, strlen($namespace . static::$nsChar))
  39. ) {
  40. $fileName = substr($class, strlen($namespace . static::$nsChar) - 1);
  41. $fileName = str_replace(
  42. static::$nsChar,
  43. DIRECTORY_SEPARATOR,
  44. ltrim($fileName, static::$nsChar),
  45. );
  46. $fileName =
  47. static::$parentPath .
  48. DIRECTORY_SEPARATOR .
  49. $path .
  50. DIRECTORY_SEPARATOR .
  51. $fileName .
  52. ".php";
  53. if (file_exists($fileName)) {
  54. include $fileName;
  55. return true;
  56. }
  57. }
  58. }
  59. return false;
  60. }
  61. }
  62. spl_autoload_register(["Loader", "load"]);