在我的服務器端我有一個梨目錄的引用include_path中,在「在/ usr /共享/梨/」。在我的應用我包括來自一個共同的庫文件,生活在「在/ usr /共享/梨/庫/」與require_once 'library/file.php'
。SPL自動加載的最佳實踐
我使用SPL自動加載最近開始,我注意到,你必須確定與包含該文件的邏輯裝載機功能。我這樣做的第一種方法是試圖包含一個文件並用@
將其壓制,以查看它是否會失敗,例如, @include 'library/file.php'
然而,我認爲主要是因爲我讀了很多關於@
是一個不好的做法,我決定手動完成這項工作,通過PATH_SEPARATOR
爆炸get_include_path
並查看目錄是否是我想要的,然後做一個file_exists
幷包括它。
像這樣:
function classLoader($class) {
$paths = explode(PATH_SEPARATOR, get_include_path());
$file = SITE_PATH . 'classes' . DS . $class . '.Class.php';
if (file_exists($file) == false)
{
$exists = false;
foreach ($paths as $path)
{
$tmp = $path . DS . 'library' . DS . 'classes' . DS . $class . '.Class.php';
if (file_exists ($tmp))
{
$exists = true;
$file = $tmp;
}
}
if (!$exists) { return false; }
}
include $file;
}
spl_autoload_register('classLoader');
難道我走錯路線?我應該剛剛完成@include
業務,還是我正朝着正確的方向去做?
是不是SPL自動加載更實用和現代的方法?或者他們基本上是一樣的東西? – 2009-12-06 07:12:32