PHP扩展类事件

时间:2010-11-03 07:40:02

标签: php class reflection extension-methods

以下是我将要讨论的代码(在这篇文章中请记住这一点):

文件: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(){
     }
}

所以,你可能知道我在做什么;它是一个应用程序/扩展系统,应用程序保存在/apps/的单独文件夹中,它的入口点是index.php

到目前为止,代码运行良好(或者,它应该,我把它写在我的头顶;))。 无论如何,我的问题是让Apps类知道所有扩展的App类。


简单的方法是在每个应用程序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;

但这听起来太资源密集,不能持续。

您怎么看?

2 个答案:

答案 0 :(得分:0)

注册方法看起来干净简单。后来的维护者(以及你自己)会清楚代码的作用,而且它不容易出错。

答案 1 :(得分:0)

注册方法没问题,你可以做

Apps::register(get_class());

MyApp构造函数中,如果有的话。

相关问题