2016-07-29 74 views
-3

我發現這個代碼可以自動加載單個目錄中的所有類,並且它工作得很好。我希望能夠擴展它來加載不同路徑(目錄)的類。下面是代碼:來自不同目錄的PHP自動加載類

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); 
       } 
      } 
     } 
    } 

那麼矮像我的index.php文件:

Autoloader::init(); 

我使用PHP 5.6

+0

你有問題嗎?這個網站是問題,而不是一個地方轉儲你的待辦事項列表,並期望別人爲你做你的工作。 –

+0

@Marc B,是的我的問題是如何擴展類來掃描多個目錄。我不指望任何人做我的工作。我提供了一段代碼,我需要幫助。如果你不想幫忙,那麼不要浪費這個空間,讓其他人說一些聰明的東西。 – Alko

+0

我們修復代碼,我們不會爲您編寫代碼,或幫助您設計系統。這是你的工作。你試着做一些事情,我們(也許)試着幫助解決它。 –

回答

0

您可以將其他目錄添加到包括路徑如果類文件與您現有的類文件具有相同的擴展名,那麼您的自動加載器將會找到它們

之前調用Autoloader:init(),做:

//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)