Woodgnome Woodgnome - 2 years ago 73
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);

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

I know this can be achieved with function references and as long as I use
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 Source

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).

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download