Zend Framework 2 - 动态加载模块及其配置

时间:2017-07-24 09:23:45

标签: php module zend-framework2 config service-locator

我试图在应用程序模块之外基于用户类型加载模块,即应用模块总是加载,因为如果用户类型为1我在application.config.php文件中提到我想要加载模块A, B和D,如果用户是类型2,我想加载模块C,E和F.

在应用程序模块的Module.php函数的onBootstrap中我动态加载模块,当我看到结果var_dump($moduleManager->loadedModules())时,它显示了正在加载的模块的数组

但我面临的问题是,即使模块已正确加载,其配置也未加载。

示例:

在我的模块A中,我有一个名为SomethingService的服务,它正在indexAction模块中IndexController的{​​{1}}中使用。但它抛出了状态

的异常
  

无法获取或创建SomethingService的实例

经过一些调试后,我发现即使加载了模块,它们的Application配置也没有加载,在module.config.php服务中无法使用。

为了解决这个问题,在我加载模块的地方,我现在使用Config方法合并,如果使用配置服务并使用以下代码覆盖配置服务

$module->getConfig()

因此,当我使用$this->serviceLocator->setAllowOverride(true); $this->serviceLocator->setService('config', $mergedConfig); $this->serviceLocator->setAllowOverride(false); 进行配置时,我发现所有模块配置都已合并,并且可在 config 数组中使用。

完成所有这些后,我仍然得到上面提到的例外。也许我在错误的位置做所有这些?

1 个答案:

答案 0 :(得分:0)

根据您的评论,如果您按application.config.php加载所有模块,它可以正常运行,问题在于动态加载模块。

而且由于Application模块引起的问题已被引导,因此您的控制器未找到SomethingService。因为您使用onBootstrap(Event $e)方法加载模块。

  在所有模块之后立即调用

onBootstrap(Event $e)方法   已被引导。

因此,首先配置了IndexController。这就是它无法找到SomethingService

的原因

我认为您需要使用init(ModuleManager $moduleManager)方法而不是onBootstrap(Event $e)加载模块。

  在模块之前调用

init(ModuleManager $moduleManager)   自举。

class Module
{
    public function init(ModuleManager $moduleManager)
    {
        // Remember to keep the init() method as lightweight as possible
    }
}