开发者

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"] = s开发者_StackOverflow中文版ome_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?


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


I think something like CommonJS or ES6 Modules for PHP would be nice. Already some ideas on that: https://groups.google.com/forum/#!topic/commonjs/sVkxbQtR-lw


  1. Modules system based on plain functions is hardly maintinable - use objects
  2. PHP since version 5 can autoload module by its name
  3. Use hierarchical system - from abstract module or interface, you will know what this module can do.
  4. If you have name in variable you can create instance like this - $foo = new $bar()

where $foo is new instance and $bar stores object name

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜