2009-07-30 18 views
1

一個類庫,我是相當新的面向對象編程...動態建築/加載在PHP

我建立什麼最終會變成是一個類的大型圖書館在我的網站上使用。顯然,在每個頁面上加載整個庫是浪費時間和精力...

所以我想要做的是在每個頁面上需要一個「配置」PHP類文件,並且能夠「調用「或」根據需要加載「其他課程 - 從而根據我的需要擴展我的課程。

從我所知道的,我不能在配置類中使用函數來簡單地包含()其他文件,因爲範圍問題。

我有什麼選擇?開發人員通常如何處理這個問題,什麼是最穩定的?

回答

3

您可以使用__autoload()或創建一個對象工廠,用於在需要時加載所需的文件。另外,如果你的庫文件存在範圍問題,你應該重構你的佈局。大多數庫都是可以在任何範圍內實例化的類集。

以下是一個非常基本的對象工廠的例子。

class ObjectFactory { 

    protected $LibraryPath; 

    function __construct($LibraryPath) { 
     $this->LibraryPath = $LibraryPath; 
    } 

    public function NewObject($Name, $Parameters = array()) { 
     if (!class_exists($Name) && !$this->LoadClass($Name)) 
      die('Library File `'.$this->LibraryPath.'/'.$Name.'.Class.php` not found.'); 
     return new $Name($this, $Parameters); 
    } 

    public function LoadClass($Name) { 
     $File = $this->LibraryPath.'/'.$Name.'.Class.php'; // Make your own structure. 
     if (file_exists($File)) 
       return include($File); 
     else return false; 
    } 
} 

// All of your library files should have access to the factory 
class LibraryFile { 

    protected $Factory; 

    function __construct(&$Factory, $Parameters) { 
     $this->Factory = $Factory; 
    } 
} 
+0

是否有教程提供了建立類庫的好建議? – johnnietheblack 2009-07-30 23:16:17