2010-11-03 97 views
1

這裏是我會說話的代碼(記住這一點,在本崗位):PHP擴展類事件

文件:index.php文件

/** 
* Base class used when created a new application. 
*/ 
class App { 
    public function do_something(){ 
    } 
} 

/** 
* Class used, among other things, to manage all apps. 
*/ 
class Apps { 
    public static function _init(){ 
     foreach(glob('apps/*') as $dir) 
      if(file_exists($dir.'/index.php') 
       include_once($dir.'/index.php'); 
    } 
} 
Apps::_init(); 

文件:MyApp的/ index.php的

class MyApp extends App { 
    /** 
     * This function overrides the the one in App... 
     */ 
    public function do_something(){ 
    } 
} 

所以,你可能知道我在做什麼;它是一個應用程序/擴展系統,是一個應用程序被保存在一個單獨的文件夾中,它的入口點是index.php。這個代碼到目前爲止效果很好(或者說,我應該把它寫在頭頂上);)。 無論如何,我的問題是讓Apps類知道所有擴展的應用程序類。


簡單的方法是在每個應用程序的index.php末尾寫下如下內容。

Apps::register('MyApp'); // for MyApp application 

它的問題是雖然它是可以理解的,但它不是自動的。例如,複製+粘貼應用程序需要修改,新開發人員更可能完全忘記該代碼(更糟糕的是,大多數代碼仍然無法使用!)。

另一個想法是_init()代碼後,使用此代碼:

$apps=array(); 
foreach(get_declared_classes() as $class) 
    if(array_search('App',class_parents($class))!==false) 
     $apps[]=$class; 

但它聽起來太耗費資源是最後一個。

您認爲如何?

回答

0

寄存器的做法是好的,你可以做

Apps::register(get_class()); 

MyApp構造函數中,如果你有一個。

+2

如果你想註冊每一個,你也可以把它放在'App'類的構造函數中,儘管你需要記得將'$ this'傳遞給'get_class'方法('Apps :: register(get_class $ this));'),如果需要在構造函數中添加其他任何內容,則需要記住在每個子類構造函數中調用'parent :: __ construct()'。 – Aether 2010-11-03 08:35:38

+0

以太......這正是我需要的!你應該已經成爲一個答案。 ;) – Christian 2010-11-03 08:59:08

0

註冊方法看起來乾淨和簡單。後面的維護者(和你自己)會明白代碼的作用,並且不太容易出錯。

+0

事實上,我覺得這是更容易出錯和維護麻煩。但這只是我能想到的一切。 – Christian 2010-11-03 07:53:43