2017-01-24 66 views
0

得到錯誤,我使用PSR-0自動加載,我知道我需要使用PSR-4,我會做後期。即使PSR-4,答案是受歡迎的。在PHP自動加載

我有使自動加載運行良好,但下面的目錄結構。

+ www/entity 
|__ /EntityGenerator 
|  |__ /Database 
|  |  |__ DatabaseConnection 
|  |  |__ DatabaseConnectionInterface 
|  |  |__ DatabaseRepositoryInterface 
|  |  
|  |__ /Exception 
| 
|__ autoload.php 
|__ index.php 

對於下面的目錄結構,它給錯誤如下

警告:要求(EntityGenerator \數據庫\ DatabaseConnection.php):未能打開流:C中沒有這樣的文件或目錄:\ WAMP \ WWW \實體\ EntityGenerator \ autoload.php第15行

+ www/entity 
| __ /EntityGenerator 
     |__ /Database 
     |  |__ DatabaseConnection 
     |  |__ DatabaseConnectionInterface 
     |  |__ DatabaseRepositoryInterface 
     |  
     |__ /Exception 
     |__ autoload.php 
     |__ index.php 

任何人都可以解釋爲什麼我越來越與第二目錄結構中的錯誤。

如果有人需要整個代碼進行測試,請找到下面的鏈接

https://github.com/channaveer/EntityGenerator

+0

你不應該鏈接到整個代碼。你應該**在你的問題中包含**相關的代碼**。最值得注意的是:看看你的autoload.php會非常有幫助。 –

+0

@Franz其實我正在計劃這個,但有時候可能會讓其他人感到困惑,究竟我在看什麼,所以想加我的代碼鏈接。無論如何,它將來會是開源的。謝謝。 –

+1

它只是我自己加載時還是隻使用相對路徑?如果是這樣,那是一個很大的否定。 – apokryfos

回答

1

您的問題,您使用的是相對路徑,這並不總是設置爲當前腳本的目錄。您需要使用絕對路徑來確保您正在加載需要加載的內容。

function autoload($className) 
{ 
    $namespaceRoot = "EntityGenerator"; 
    $className = ltrim($className, '\\'); 
    if (strpos($className,$namespaceRoot) !== 0) { return; } //Not handling other namespaces 
    $className = substr($className, strlen($namespaceRoot)); 
    $fileName = ''; 
    $namespace = ''; 
    if ($lastNsPos = strrpos($className, '\\')) { 
     $namespace = substr($className, 0, $lastNsPos); 
     $className = substr($className, $lastNsPos + 1); 
     $fileName = str_replace('\\', DIRECTORY_SEPARATOR, $namespace) . DIRECTORY_SEPARATOR; 
    } 
    $fileName .= str_replace('_', DIRECTORY_SEPARATOR, $className) . '.php'; 
    require __DIR__.DIRECTORY_SEPARATOR.$fileName; //absolute path now 
} 
spl_autoload_register('autoload'); 

__DIR__保證返回當前運行腳本所在的目錄。

+0

我試着用你的變化,並得到了當我在自動加載「C:\ WAMP \ WWW \實體\ EntityGenerator \ EntityGenerator \數據庫\ DatabaseConnection.php」遙相呼應以下。即使現在與2結構相同的問題。錯誤如下:「警告:require(C:\ wamp \ www \ entity \ EntityGenerator \ EntityGenerator \ Database \ DatabaseConnection.php):未能打開流」。你能幫我解決這個問題嗎? –

+0

@ChannaveerHakari你的問題在於你將自動加載器移動到名稱空間中。通常自動加載器位於命名空間之外。但是,您可以通過指定根名稱空間以及您已經位於的目錄來修復該問題。檢查更新的代碼 – apokryfos

+0

感謝您的工作。只是想知道不同的方式。你的回答讓我明白了 –

1

這是因爲目錄結構。您正試圖加載EntityGenerator \ Database \ DatabaseConnection。它與第一個例子中的路徑相匹配,但不適用於第二個例子。看看autoload.php的路徑。它正在尋找路徑。 EntityGenerator是www /實體中的有效路徑,它是autoload.php的路徑。但在第二個例子中不適用於www/entity/EntityGenerator。

+0

當I **在自動載入函數中回顯路徑時,兩個目錄結構都顯示相同的路徑。你對此有何看法? –

+0

路徑應該正確的,我同意,但autoload.php不能訪問在第二個例子是路徑引起/沒有EntityGenerator路徑在網絡/實體EntityGenerator哪裏是你的autoload.php的路徑。 只要把附近的第二個例子autoload.php文件,並要求這是你從「回聲」獲取路徑。你會看到什麼是錯的。如果可以的話,嘗試使用require/include的絕對路徑。 –