Autoloader.php 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869
  1. <?php
  2. /**
  3. * This file is part of workerman.
  4. *
  5. * Licensed under The MIT License
  6. * For full copyright and license information, please see the MIT-LICENSE.txt
  7. * Redistributions of files must retain the above copyright notice.
  8. *
  9. * @author walkor<walkor@workerman.net>
  10. * @copyright walkor<walkor@workerman.net>
  11. * @link http://www.workerman.net/
  12. * @license http://www.opensource.org/licenses/mit-license.php MIT License
  13. */
  14. namespace Workerman;
  15. /**
  16. * Autoload.
  17. */
  18. class Autoloader
  19. {
  20. /**
  21. * Autoload root path.
  22. *
  23. * @var string
  24. */
  25. protected static $_autoloadRootPath = '';
  26. /**
  27. * Set autoload root path.
  28. *
  29. * @param string $root_path
  30. * @return void
  31. */
  32. public static function setRootPath($root_path)
  33. {
  34. self::$_autoloadRootPath = $root_path;
  35. }
  36. /**
  37. * Load files by namespace.
  38. *
  39. * @param string $name
  40. * @return boolean
  41. */
  42. public static function loadByNamespace($name)
  43. {
  44. $class_path = str_replace('\\', DIRECTORY_SEPARATOR, $name);
  45. if (strpos($name, 'Workerman\\') === 0) {
  46. $class_file = __DIR__ . substr($class_path, strlen('Workerman')) . '.php';
  47. } else {
  48. if (self::$_autoloadRootPath) {
  49. $class_file = self::$_autoloadRootPath . DIRECTORY_SEPARATOR . $class_path . '.php';
  50. }
  51. if (empty($class_file) || !is_file($class_file)) {
  52. $class_file = __DIR__ . DIRECTORY_SEPARATOR . '..' . DIRECTORY_SEPARATOR . "$class_path.php";
  53. }
  54. }
  55. if (is_file($class_file)) {
  56. require_once($class_file);
  57. if (class_exists($name, false)) {
  58. return true;
  59. }
  60. }
  61. return false;
  62. }
  63. }
  64. spl_autoload_register('\Workerman\Autoloader::loadByNamespace');