Autoloader.php 2.2 KB

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