PHP autoload classes from different directories

2019-09-22 03:06发布

问题:

I have found this code that autoloads all classes within single directory, and it works pretty good. I would like to be able to extend it a bit to load classes from different paths (directories). Here is the code:

  define('PATH', realpath(dirname(__file__)) . '/classes') . '/';
  define('DS', DIRECTORY_SEPARATOR);

  class Autoloader
  {
      private static $__loader;


      private function __construct()
      {
          spl_autoload_register(array($this, 'autoLoad'));
      }


      public static function init()
      {
          if (self::$__loader == null) {
              self::$__loader = new self();
          }

          return self::$__loader;
      }


      public function autoLoad($class)
      {
          $exts = array('.class.php');

          spl_autoload_extensions("'" . implode(',', $exts) . "'");
          set_include_path(get_include_path() . PATH_SEPARATOR . PATH);

          foreach ($exts as $ext) {
              if (is_readable($path = BASE . strtolower($class . $ext))) {
                  require_once $path;
                  return true;
              }
          }
          self::recursiveAutoLoad($class, PATH);
      }

      private static function recursiveAutoLoad($class, $path)
      {
          if (is_dir($path)) {
              if (($handle = opendir($path)) !== false) {
                  while (($resource = readdir($handle)) !== false) {
                      if (($resource == '..') or ($resource == '.')) {
                          continue;
                      }

                      if (is_dir($dir = $path . DS . $resource)) {
                          continue;
                      } else
                          if (is_readable($file = $path . DS . $resource)) {
                              require_once $file;
                          }
                  }
                  closedir($handle);
              }
          }
      }
  }

then in runt in my index.php file like :

Autoloader::init();

I'm using php 5.6

回答1:

You can add the other directories to the include path and if the class files have the same extension as your existing class files, your autoloader will find them

Before calling Autoloader:init(), do:

//directories you want the autoloader to search through
$newDirectories = ['/path/to/a', '/path/to/b'];
$path = get_include_path().PATH_SEPARATOR;
$path .= implode(PATH_SEPARATOR, $newDirectories);
set_include_path($path)


标签: php autoload