drs7798 2011-08-31 12:35
浏览 45
已采纳

PHP中基于模块的系统 - 如何?

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?

  • 写回答

3条回答 默认 最新

  • dongtang2376 2011-08-31 12:39
    关注

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

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥60 版本过低apk如何修改可以兼容新的安卓系统
  • ¥25 由IPR导致的DRIVER_POWER_STATE_FAILURE蓝屏
  • ¥50 有数据,怎么建立模型求影响全要素生产率的因素
  • ¥50 有数据,怎么用matlab求全要素生产率
  • ¥15 TI的insta-spin例程
  • ¥15 完成下列问题完成下列问题
  • ¥15 C#算法问题, 不知道怎么处理这个数据的转换
  • ¥15 YoloV5 第三方库的版本对照问题
  • ¥15 请完成下列相关问题!
  • ¥15 drone 推送镜像时候 purge: true 推送完毕后没有删除对应的镜像,手动拷贝到服务器执行结果正确在样才能让指令自动执行成功删除对应镜像,如何解决?