Woodgnome Woodgnome - 7 months ago 14
PHP Question

Module based system in PHP - how to?

I have a PHP web application where I've made a little module system, that basically works like this:

Each module has it's own file, filename can be anything, but does not matter (for the sake of logic I named the filename is the same as the module name). The content of a module could look like this:

$MODULE["name"] = "some_module";
$MODULE["description"] = "This module does some things";
$MODULE["required"] = false;
$MODULE["module_specific_var"] = some_function_that_returns_some_value();


I have a global $MODULES array where I read all modules into:

foreach ($modules_list as $module_filename){
if (isset($MODULE)) unset($MODULE);
include($module_path."/".$module_filename);
$MODULES[$MODULE["name"]] = $MODULE;
}


Now this is pretty simple and have been more than enough for my needs... Until now... Now I need a module specific function and that doesn't work with associative arrays (as far as I know of). What I'd like is something along the lines of being able to call
$MODULES["name_of_module"]["name_of_module_specific_function"]();


I know this can be achieved with function references and as long as I use
include()
for each module, any functions defined in the module files will be available in global space - this may cause naming issues though, so bad idea.

Alternatively I make each module a class, something along the lines of:

class module_name {
var $name = "some_module";
var $description = "This module does some things";
var $required = false;
var $module_specific_var = some_function_that_returns_some_value();
function module_specific_function(){
}
}


Since I've already got a fair bit of code, my question is - is there an alternative to making all the modules class based, which avoids both the problem of name conflicts and allows me to keep the current module system fairly intact?

Answer

OO is the way to go here. Make a Module base class, and extend that if you need module specific functions.

If you map the class names to your file names, you can even use an autoloader so you won't have to include() everything. It would also be nice to have a central Singleton class to keep track of your module instances (to avoid having to use globals, which is a deprecated practice).