2016-07-29 6 views
-3

이 코드는 단일 클래스 내에서 모든 클래스를 자동으로로드한다는 것을 알았습니다. 다른 경로 (디렉토리)에서 클래스를로드하려면이 클래스를 약간 확장 할 수 있어야합니다. 여기 코드는 다음과 같습니다다른 디렉토리에있는 PHP 자동로드 클래스

처럼 내 index.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); 
       } 
      } 
     } 
    } 

: 내가 사용

Autoloader::init(); 

당신은 포함 경로로 다른 디렉토리를 추가 할 수 있습니다 5.6

+0

질문이 있으십니까? 이 사이트는 귀하의 할 일 목록을 버리고 다른 누군가가 당신을 위해 일하기를 기대하는 곳이 아닙니다. –

+0

@Marc B, 네, 내 질문은 어떻게 여러 디렉토리를 스캔 클래스를 확장하는 것입니다. 나는 아무도 내 일을 기대하지 않는다. 코드 조각을 제공했으며 도움이 필요합니다. 도움을 받고 싶지 않다면,이 공간을 낭비하지 말고 다른 누군가가 똑똑하게 말하게하십시오. – Alko

+0

코드를 수정했지만 작성하지 않거나 시스템을 설계하는 데 도움을줍니다. 그것이 당신의 직업입니다. 너는 무언가를 시도하고, 우리는 (어쩌면) 그것을 고치는 것을 시도한다. –

답변

0

PHP 클래스 파일이 기존 클래스 파일과 동일한 확장자를 가진 경우 오토로더는 해당 파일을 찾습니다.

전에 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)