Guest User

Untitled

a guest
Jun 18th, 2018
181
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.01 KB | None | 0 0
  1. <?php
  2. /**
  3. * Simple autoloader.
  4. *
  5. * @copyright (c) 2011 Evgeny Vrublevsky <veg@tut.by>
  6. */
  7. class autoloader
  8. {
  9. protected static $pathes = array();
  10. protected static $registered = false;
  11.  
  12. static function init($path = '')
  13. {
  14. autoloader::register();
  15. if(!empty($path)) autoloader::add_path($path);
  16. }
  17.  
  18. static function add_path($path, $prefix = '')
  19. {
  20. $prefix = strtolower($prefix);
  21. if(!isset(autoloader::$pathes[$prefix]))
  22. {
  23. autoloader::$pathes[$prefix] = array();
  24. }
  25. $path = str_replace('\\', '/', $path);
  26. if($path{strlen($path)-1} !== '/') $path .= '/';
  27. autoloader::$pathes[$prefix][] = $path;
  28. }
  29.  
  30. static function register()
  31. {
  32. if (autoloader::$registered) return;
  33. if (!spl_autoload_register(array('autoloader','load')))
  34. {
  35. throw new Exception('Could not register autoload function');
  36. }
  37. autoloader::$registered = true;
  38. }
  39.  
  40. static function unregister()
  41. {
  42. if (!autoloader::$registered) return;
  43. if (!spl_autoload_unregister(array('autoloader','load')))
  44. {
  45. throw new Exception('Could not unregister autoload function');
  46. }
  47. autoloader::$registered = false;
  48. }
  49.  
  50. static function resolve_path($path, $parts)
  51. {
  52. $last = end($parts);
  53. while (count($parts) > 0 && is_dir($path.$parts[0]))
  54. {
  55. $path .= array_shift($parts) . '/';
  56. }
  57. $filename = (count($parts) == 0) ? $last : implode('_', $parts);
  58. return $path . $filename . '.php';
  59. }
  60.  
  61. static function load($class)
  62. {
  63. if (!preg_match("/^[a-z0-9_]+$/i", $class)) return false;
  64. if (class_exists($class, false)) return true;
  65. $parts = explode('_', strtolower($class));
  66. // Start searching without prefix
  67. $prefix = '';
  68. while(count($parts) > 0)
  69. {
  70. if(isset(autoloader::$pathes[$prefix]))
  71. {
  72. foreach (autoloader::$pathes[$prefix] as $path)
  73. {
  74. $file = autoloader::resolve_path($path, $parts);
  75. if (file_exists($file))
  76. {
  77. include_once($file);
  78. return true;
  79. }
  80. }
  81. }
  82. // Trying with prefix
  83. $prefix = empty($prefix)
  84. ? array_shift($parts)
  85. : ($prefix.'_'.array_shift($parts));
  86. }
  87. return false;
  88. }
  89. }
Add Comment
Please, Sign In to add comment