Advertisement
MSupian

PHP Class Autoloader

Jan 20th, 2017
127
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
PHP 4.29 KB | None | 0 0
  1. <?php
  2. /**
  3.  *      // set configuration settings
  4.  *     
  5.  *      autoloader([[
  6.  *          'debug' => true, // set debug mode on/off
  7.  *          'basepath' => '/var/www/myproject', // set project base path
  8.  *          'extensions' => ['.php'], // set allowed class extension(s) to load
  9.  *          // 'extensions' => ['.php', '.php4', '.php5'], // example of multiple extensions
  10.  *          // use namespace if autoloader function is in namespace for registering autoloader
  11.  *          'namespace' => 'My\Namespace',
  12.             'verbose' => false // will print internal messages (for debugging)
  13.  *      ]]);
  14.  *
  15.  *      // add class paths to autoload
  16.  *      autoloader([
  17.  *          'lib', // really '/var/www/myproject/lib' when using basepath in config settings
  18.  *          'models/data' // really '/var/www/myproject/models/data' when using basepath in config settings
  19.  *      ]);
  20.  *
  21.  *      // get array registered class paths (when in debug mode any autoloaded classes will show up as 'loaded')
  22.  *      $registered_class_paths = autoloader();
  23.  *
  24.  *      // or configuration settings AND class paths to autoload, example:
  25.  *      autoloader([
  26.  *          // set configuration settings
  27.  *          [
  28.  *              'debug' => true,
  29.  *              'basepath' => '/var/www/myproject'
  30.  *          ],
  31.  *          // set class paths to autoload
  32.  *          'lib',
  33.  *          'models/data'
  34.  *      ]);
  35.  */
  36.  
  37. function Autoloader($class_paths = NULL, $use_base_dir = true){
  38.     static $is_init = false;
  39.  
  40.     static $conf = [
  41.         'basepath' => '',
  42.         'debug' => false,
  43.         'extensions' => ['.php'], // multiple extensions ex: ['.php', '.class.php']
  44.         'namespace' => '',
  45.         'verbose' => false
  46.     ];
  47.  
  48.     static $paths = [];
  49.  
  50.     // autoloader(); returns paths (for debugging)  
  51.     if(\is_null($class_paths)){
  52.         return $paths;
  53.     }
  54.  
  55.     if(\is_array($class_paths) && isset($class_paths[0]) && \is_array($class_paths[0])) // conf settings
  56.     {
  57.         foreach($class_paths[0] as $k => $v)
  58.         {
  59.             if(isset($conf[$k]) || \array_key_exists($k, $conf))
  60.             {
  61.                 $conf[$k] = $v; // set conf setting
  62.             }
  63.         }
  64.        
  65.         unset($class_paths[0]); // rm conf from class paths
  66.     }
  67.  
  68.     // init autoloader
  69.     if(!$is_init){
  70.         \spl_autoload_extensions(implode(',', $conf['extensions']));
  71.         \spl_autoload_register(NULL, false); // flush existing autoloads
  72.         $is_init = true;
  73.     }
  74.  
  75.     if($conf['debug']){
  76.         $paths['conf'] = $conf; // add conf for debugging
  77.     }
  78.     // autoload class
  79.     if(!\is_array($class_paths)){
  80.         // class with namespaces, ex: 'MyPack\MyClass' => 'MyPack/MyClass' (directories)
  81.         $class_path = \str_replace('\\', \DIRECTORY_SEPARATOR, $class_paths);
  82.  
  83.         foreach($paths as $path){
  84.             // do not allow cached 'loaded' paths
  85.             if(!\is_array($path)){
  86.                 foreach($conf['extensions'] as &$ext){
  87.                     $ext = \trim($ext);
  88.  
  89.                     if(\file_exists($path . $class_path . $ext)){
  90.                         if($conf['debug']){
  91.                             if(!isset($paths['loaded']))
  92.                             {
  93.                                 $paths['loaded'] = [];
  94.                             }
  95.  
  96.                             $paths['loaded'][] = $path . $class_path . $ext;
  97.                         }
  98.  
  99.                         require $path . $class_path . $ext;
  100.  
  101.                         if($conf['verbose']){
  102.                             echo '<div>' . __METHOD__ . ': autoloaded class "' . $path
  103.                                 . $class_path . $ext . '"</div>';
  104.                         }
  105.  
  106.                         return true;
  107.                     }
  108.                 }
  109.  
  110.                 if($conf['verbose']){
  111.                     echo '<div>' . __METHOD__ . ': failed to autoload class "' . $path
  112.                         . $class_path . $ext . '"</div>';
  113.                 }
  114.             }
  115.         }
  116.  
  117.         return false; // failed to autoload class
  118.     } else {
  119.         // register class path
  120.         $is_unregistered = true;
  121.  
  122.         if(count($class_paths) > 0){
  123.             foreach($class_paths as $path){
  124.                 $tmp_path = ( $use_base_dir ? \rtrim($conf['basepath'], \DIRECTORY_SEPARATOR)
  125.                     . \DIRECTORY_SEPARATOR : '' ) . \trim(\rtrim($path, \DIRECTORY_SEPARATOR))
  126.                     . \DIRECTORY_SEPARATOR;
  127.  
  128.                 if(!\in_array($tmp_path, $paths)){
  129.                     $paths[] = $tmp_path;
  130.  
  131.                     if($conf['verbose']){
  132.                         echo '<div>' . __METHOD__ . ': registered path "' . $tmp_path . '"</div>';
  133.                     }
  134.                 }
  135.             }
  136.  
  137.             if(\spl_autoload_register(( strlen($conf['namespace']) > 0 // add namespace
  138.                 ? rtrim($conf['namespace'], '\\') . '\\' : '' ) . 'autoloader', (bool)$conf['debug'])){
  139.                 if($conf['verbose']){
  140.                     echo '<div>' . __METHOD__ . ': autoload registered</div>';
  141.                 }
  142.  
  143.                 $is_unregistered = false; // flag unable to register
  144.             } else if($conf['verbose']){
  145.                 echo '<div>' . __METHOD__ . ': autoload register failed</div>';
  146.             }
  147.         }
  148.  
  149.         return !$conf['debug'] ? !$is_unregistered : $paths;
  150.     }
  151. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement