Autoloader.php 2.2 KB

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