Autoloader.php 2.0 KB

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