gsi*_*ank 2 events module zend-framework2 servicemanager
我需要在任何MvcEvent::EVENT_BOOTSTRAP侦听器执行之前执行一些代码.显然Module::onBootstrap不是一个选择.我以下面的代码结尾:
class Module
{
function init(\Zend\ModuleManager\ModuleManager $moduleManager)
{
$moduleManager->getEventManager()->attach(
MvcEvent::EVENT_BOOTSTRAP, array(ClassX, 'StaticMethodOfClassX'), 20000);
}
}
Run Code Online (Sandbox Code Playgroud)
我不希望硬编码array(ClassX, 'StaticMethodOfClassX')引用,但从服务管理器获取它.我的问题是我不知道如何在模块的init方法中获取服务管理器引用.有帮助吗?或者现在在ZF2中这是不可能的?无论这种模式或意见的变体是什么也将是欣赏;)
编辑:
我将澄清"显然Module :: onBootstrap不是一个选项",cos可能不是那么琐碎;)
触发Module::onBootstrap事件时执行模块方法MvcEvent::EVENT_BOOTSTRAP,但每个模块的Module::onBootstrap方法附加到该事件取决于加载模块的顺序.由于,特定Module::onBootstrap方法的执行顺序取决于其他模块的存在以及其他模块如何影响特定模块的加载顺序.除此之外,任何附加到MvcEvent::EVENT_BOOTSTRAP优先级大于1 的事件的侦听器都将在任何模块Module::onBootstrap方法之前执行,例如 ViewManager::onBootstrap侦听器.所以,要实现我想要的
我需要在任何
MvcEvent::EVENT_BOOTSTRAP侦听器执行之前执行一些代码
模块obBootstrap方法不是一个选项.
这是一个非常古老的帖子,但由于没有接受答案,我最近需要达到同样的目的,我想我会分享我的解决方案.
我在触发Bootstrap事件之前需要访问ServiceManager的原因是我可以使用从数据库中检索的值来操作合并配置.
问题:
Zend 文档中的示例显示了如何操作合并配置,但在那个特定时间,服务管理器是空的,因此无法检索数据库适配器等内容.
方案:
在您的模块类中,实现接口InitProviderInterface并添加适当的方法.
public function init(ModuleManagerInterface $moduleManager)
{
$eventManager = $moduleManager->getEventManager();
$eventManager->attach(ModuleEvent::EVENT_LOAD_MODULES_POST, [$this, 'onLoadModulesPost']);
}
Run Code Online (Sandbox Code Playgroud)
该EVENT_LOAD_MODULES_POST活动将在之后被调用EVENT_MERGE_CONFIG事件,但前EVENT_BOOTSTRAP触发事件.此时,在此特定时间,ServiceManager将包含您要访问的所有工厂,可调用类.
你的回调方法可能看起来像.
public function onLoadModulesPost(ModuleEvent $event)
{
/* @var $serviceManager \Zend\ServiceManager\ServiceManager */
$serviceManager = $event->getParam('ServiceManager');
$configListener = $event->getConfigListener();
$configuration = $configListener->getMergedConfig(false);
$someService = $serviceManager->get('Your/Custom/Service');
$information = $someService->fetchSomeInformation();
$configuration = array_merge($configuration, $information);
$configListener->setMergedConfig($configuration);
$event->setConfigListener($configListener);
$serviceManager->setAllowOverride(true);
$serviceManager->setService('Config', $configuration);
$serviceManager->setAllowOverride(false);
}
Run Code Online (Sandbox Code Playgroud)