Autoloader.php 1.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061
  1. <?php
  2. namespace Workerman;
  3. // 定义Workerman根目录
  4. if(!defined('WORKERMAN_ROOT_DIR'))
  5. {
  6. define('WORKERMAN_ROOT_DIR', realpath(__DIR__ . '/../'));
  7. }
  8. // 包含常量定义文件
  9. require_once WORKERMAN_ROOT_DIR.'/Workerman/Lib/Constants.php';
  10. /**
  11. * 自动加载类
  12. * @author walkor<walkor@workerman.net>
  13. */
  14. class Autoloader
  15. {
  16. // 应用的初始化目录,作为加载类文件的参考目录
  17. protected static $_appInitPath = '';
  18. /**
  19. * 设置应用初始化目录
  20. * @param string $root_path
  21. * @return void
  22. */
  23. public static function setRootPath($root_path)
  24. {
  25. self::$_appInitPath = $root_path;
  26. }
  27. /**
  28. * 根据命名空间加载文件
  29. * @param string $name
  30. * @return boolean
  31. */
  32. public static function loadByNamespace($name)
  33. {
  34. // 相对路径
  35. $class_path = str_replace('\\', DIRECTORY_SEPARATOR ,$name);
  36. // 先尝试在应用目录寻找文件
  37. $class_file = self::$_appInitPath . '/' . $class_path.'.php';
  38. // 文件不存在,则在workerman根目录中寻找
  39. if(!is_file($class_file))
  40. {
  41. $class_file = WORKERMAN_ROOT_DIR . DIRECTORY_SEPARATOR . "$class_path.php";
  42. }
  43. // 找到文件
  44. if(is_file($class_file))
  45. {
  46. // 加载
  47. require_once($class_file);
  48. if(class_exists($name, false))
  49. {
  50. return true;
  51. }
  52. }
  53. return false;
  54. }
  55. }
  56. // 设置类自动加载回调函数
  57. spl_autoload_register('\Workerman\Autoloader::loadByNamespace');