Advertisement
Guest User

php simple autoload

a guest
Jul 21st, 2012
119
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
PHP 1.71 KB | None | 0 0
  1. <?php
  2.  /**
  3.  * @file   autoload.php
  4.  * @author  <[email protected]>
  5.  * @date   Sat Jul 21 13:37:50 2012
  6.  * @see    http://swwwfactory.blogspot.com/
  7.  *
  8.  * @brief  Simple autoload your classes
  9.  *
  10.  *
  11.  */
  12. namespace com\my\stuff;
  13.  
  14. class Autoload
  15. {
  16.     static protected $db = [
  17.          //add here my classes
  18.          'com\my\stuff\Example' => 'path/to/example.php',
  19.          'com\my\another\stuff\Example' => 'path/to/another.foo.bar.example.php'
  20.         ];
  21.  
  22.     public static function init()
  23.     {
  24.         return spl_autoload_register(__NAMESPACE__ .'\Autoload::handler');
  25.     }
  26.  
  27.     public static function handler($name)
  28.     {
  29.         $db = self::$db;
  30.         if (isset($db[$name])) {
  31.             $module = __DIR__ . '/' . $db[$name];
  32.             //uncomment this to debug
  33.             //echo 'try load:', $module, ' for class:', $name, '<br>';
  34.             //echo '<pre>', debug_print_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS, 0),
  35.             //    '</pre>';
  36.             //$old = get_declared_classes();
  37.             include $module;
  38.             //uncomment this to debug
  39.             //echo '<pre>',
  40.             //    print_r(array_diff(get_declared_classes(), $old), true),
  41.             //    '</pre>';
  42.             //echo 'done load.', '<br><br>';
  43.             return true;
  44.         }
  45.         return false;
  46.     }
  47.  
  48.     public static function testClasses()
  49.     {
  50.         array_walk(
  51.             self::$db,
  52.             function ($elem, $key) {
  53.                        return class_exists($key);
  54.             }
  55.         );
  56.     }
  57.  
  58.     public static function getLoadMap()
  59.     {
  60.         return self::$db;
  61.     }
  62.  
  63. }
  64.  
  65. Autoload::init();
  66. //uncomment this for autoload tests
  67. //Autoload::testClasses();
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement