2014-03-30 35 views
0

我剛開始在我的應用程序中使用自動加載器延遲加載,並且與名稱空間發生衝突。自動加載器試圖加載諸如new DateTime()之類的東西並且失敗。有沒有什麼竅門讓我的自動加載器只有我自己的命名空間類?限制我的spl_autoloader只加載我名字空間中的類?

這是我目前的代碼。我懷疑這是一個爛攤子,但我沒有看到只是如何糾正它:

<?php namespace RSCRM; 
class Autoloader { 
    static public function loader($className) { 
     $filename = dirname(__FILE__) .'/'. str_replace("\\", '/', $className) . ".php"; 
     if (file_exists($filename)) { 
      include_once($filename); 
      if (class_exists($className)) { 
       return TRUE; 
      } 
     } 
     return FALSE; 
    } 
} 
spl_autoload_register('\RSCRM\Autoloader::loader'); 

快樂RTM,如果有人可以指向一個堅實的例子。

回答

1

我用的實際上是從使用單元測試幾個AuraPHP庫的磁帶自動加載機適應:

<?php 
spl_autoload_register(function ($class) { 

    // a partial filename 
    $part = str_replace('\\', DIRECTORY_SEPARATOR, $class) . '.php'; 

    // directories where we can find classes 
    $dirs = array(
     __DIR__ . DIRECTORY_SEPARATOR . 'src', 
     __DIR__ . DIRECTORY_SEPARATOR . 'tests' . DIRECTORY_SEPARATOR . 'src', 
     __DIR__ . DIRECTORY_SEPARATOR . 'install' . DIRECTORY_SEPARATOR . 'src', 
    ); 

    // go through the directories to find classes 
    foreach ($dirs as $dir) { 

     $file = $dir . DIRECTORY_SEPARATOR . $part; 
     if (is_readable($file)) { 
      require $file; 
      return; 
     } 
    } 
}); 

只需確保的「$迪爾斯」數組值指向你的命名空間代碼根。

您還可以查看PSR-0示例實現(http://www.php-fig.org/psr/psr-0/)。

您可能還想看看現有的自動加載器,如Aura.Autoload或Symfony ClassLoader組件,雖然這些可能是矯枉過正的,取決於您的要求。

我希望這會有所幫助。

+0

謝謝@Burnsy。 –

相關問題