2012-10-11 76 views
0

有一件經常讓我困擾的事情是我沒有PHP中的類路徑和依賴管理系統。有沒有可以建議的框架?我聽說梨是一個很好的系統,但我想知道還有什麼。PHP依賴和類路徑管理

一個例子會說......我有文件A.php,B.php和C.php,其中A取決於B誰取決於C.其中所有3位於不同的文件夾中。

所以一旦A.php包含B.php,它也需要包含C.php。在B.php中鍵入require_once(「C.php」)不起作用,因爲require_once必須調用A.php和C.php之間的相對路徑,而不是B.php和C.php之間的相對路徑,這很煩人。

+0

爲什麼不使用的命名空間與類自動加載? –

+0

聽起來就像你需要一個自動加載器....並且包括/需要總是可以使用絕對路徑 –

+0

作曲家:http://getcomposer.org – igorw

回答

2

我建議你嘗試doctrine類加載器項目。

Here你可以找到官方文檔。

爲了使用這個庫,你需要一個版本的PHP具有命名空間的支持(當時> = 5.3)

3

對於這個問題,我傾向於選擇自動加載磁帶機。製作一個強大的腳本來掃描一些給定的文件並建立映射到文件中的類的列表並不難。下面是我如何做到這一點:

$classes = array(); 

//this is the main function, give it a file and it will map any 
//classes it finds in the file to the path. How you find the files 
//is up to you, only you know your directory structure, but I 
//generally set up a few folders that hold my classes, and have 
//the script recurse through those passing each file it finds through 
//this function 
function get_php_classes($file) { 
    global $classes; 
    $php_code = file_get_contents($file); 
    $tokens = token_get_all($php_code); 
    $count = count($tokens); 

    //uses phps own parsing to figure out classes 
    //this has the advantage of being able to find 
    //multiple classes contained in one file 
    for ($i = 2; $i < $count; $i++) { 
     if ( $tokens[$i - 2][0] == T_CLASS 
      && $tokens[$i - 1][0] == T_WHITESPACE 
      && $tokens[$i][0] == T_STRING) { 

      $class_name = $tokens[$i][1]; 
      //now we map a class to a file ie 'Autoloader' => 'C:\project\Autoloader.cls.php' 
      $classes[$class_name] = $file; 
     } 
    } 
} 

$fh = fopen('file_you_want_write_map_to', 'w'); 
fwrite($fh, serialize($classes)); 
fclose($fh); 

就是這樣產生的文件映射腳本,你運行它隨時一旦你添加一個新類。這裏是一個可以用來自動加載實際的應用程序代碼:

class Autoloader { 
    private $class_map; 

    public function __construct() { 

     //you could also move this out of the class and pass it in as a param 
     $this->class_map = unserialize(file_get_contents($file_you_wrote_to_earlier)); 
     spl_autoload_register(array($this, 'load')); 
    } 

    private function load($className) { 
     //and now that we did all that work in the script, we 
     //we just look up the name in the map and get the file 
     //it is found in 
     include $this->class_map[$className]; 
    } 
} 

還有很多更是可以用這個方式實現,即安全檢查各種事情,如在構建自動加載列表,確保發現的重複類該文件試圖包括他們之前存在,等等