这里是我会说话的代码(记住这一点,在本岗位):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;
但它听起来太耗费资源是最后一个。
您认为如何?
如果你想注册每一个,你也可以把它放在'App'类的构造函数中,尽管你需要记得将'$ this'传递给'get_class'方法('Apps :: register(get_class $ this));'),如果需要在构造函数中添加其他任何内容,则需要记住在每个子类构造函数中调用'parent :: __ construct()'。 – Aether 2010-11-03 08:35:38
以太......这正是我需要的!你应该已经成为一个答案。 ;) – Christian 2010-11-03 08:59:08