PHP extended class event
Here's the code I'll be talking on (keep this in mind throughout this post):
File: 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 {
开发者_JAVA技巧public static function _init(){
foreach(glob('apps/*') as $dir)
if(file_exists($dir.'/index.php')
include_once($dir.'/index.php');
}
}
Apps::_init();
File: MyApp/index.php
class MyApp extends App {
/**
* This function overrides the the one in App...
*/
public function do_something(){
}
}
So, you probably know what I'm doing; it's an application/extension system, were an application is kept in a separate folder in /apps/
and it's entry point is index.php
.
The code, so far, works nicely (or, well it should, I wrote it off the top of my head ;)). Anyway, my issue is to make Apps class aware of all the extended App classes.
The easy way would be to write something like the following at the end of each application's index.php
.
Apps::register('MyApp'); // for MyApp application
The problem with it is that although it's understandable, it is not automated. For instance, copy+pasting an application needs that modification, and new developers are more likely to completely forget that code (and even worse, most of the code still works without it!).
Another idea was to use this code after the code in _init()
:
$apps=array();
foreach(get_declared_classes() as $class)
if(array_search('App',class_parents($class))!==false)
$apps[]=$class;
But it sounds too resource-intensive that last one.
What do you think?
The register approach is okay, you could do
Apps::register(get_class());
inside the MyApp
constructor, if you have one.
The register approach looks clean and simple. It will be clear to later maintainers (and to yourself) what the code does and it's less error-prone.
精彩评论