Autoloader.php 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172
  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. * @var string
  23. */
  24. protected static $_autoloadRootPath = '';
  25. /**
  26. * Set autoload root path.
  27. * @param string $root_path
  28. * @return void
  29. */
  30. public static function setRootPath($root_path)
  31. {
  32. self::$_autoloadRootPath = $root_path;
  33. }
  34. /**
  35. * Load files by namespace.
  36. * @param string $name
  37. * @return boolean
  38. */
  39. public static function loadByNamespace($name)
  40. {
  41. $class_path = str_replace('\\', DIRECTORY_SEPARATOR ,$name);
  42. if(strpos($name, 'Workerman\\') === 0)
  43. {
  44. $class_file = __DIR__.substr($class_path, strlen('Workerman')).'.php';
  45. }
  46. else
  47. {
  48. if(self::$_autoloadRootPath)
  49. {
  50. $class_file = self::$_autoloadRootPath . DIRECTORY_SEPARATOR . $class_path.'.php';
  51. }
  52. if(empty($class_file) || !is_file($class_file))
  53. {
  54. $class_file = __DIR__.DIRECTORY_SEPARATOR.'..'.DIRECTORY_SEPARATOR . "$class_path.php";
  55. }
  56. }
  57. if(is_file($class_file))
  58. {
  59. require_once($class_file);
  60. if(class_exists($name, false))
  61. {
  62. return true;
  63. }
  64. }
  65. return false;
  66. }
  67. }
  68. spl_autoload_register('\Workerman\Autoloader::loadByNamespace');