I need my ZF2 module to wait until all modules have been loaded that might overwrite my module's config. I then need to extract some values from the merged config and attach a listener to the shared event manager.
In my module I have this;
public function init(ModuleManager $moduleManager)
{
// Listen for when all other modules have been loaded.
$eventManager = $moduleManager->getEventManager();
$eventManager->attach(ModuleEvent::EVENT_LOAD_MODULES_POST, array($this, 'onModulesLoadedPost'));
}
private function onModulesLoadedPost(ModuleEvent $event)
{
$config = $event->getConfigListener()->getMergedConfig(false)['MyConfigKey'];
$sharedEventManager = // HELP, How do i get the shared event manager here?
// listen for new roles (if configured)
if ($config['new_role_event_id'] != '') {
$param = $config['new_role_event_param'];
$sharedEventManager->attach($config['new_role_event_id'], $config['new_role_event'], function($e) use($serviceManager, $param) {
$role = $e->getParam($param)->getId();
$service = $serviceManager->get('CivAccess\AclService');
$service->addRole($role, 'user');
}, 100);
}
}
In the onModulesLoadedPost function how do I access the shared event manager? (You can see I also need to grab the service manager.)
答案 0 :(得分:0)
如果您需要监听器中的服务管理器,则应使用MvcEvent::EVENT_BOOTSTRAP
。当引导事件发生时,所有配置已经合并在一起。
您可以使用onBootstrap
方法检查配置,并在需要时添加侦听器。
public function onBootstrap(MvcEvent $event)
{
$application = $event->getApplication();
$eventManager = $application->getEventManager()->getSharedManager();
$config = $application->getServiceManager()->get('Config');
if (! empty($config['new_role_event_id'])) {
$eventManager->attach($config['new_role_event_id'], $config['new_role_event'], [$this, 'addAclRole']);
}
}
public function addAclRole(MvcEvent $event)
{
$serviceManager = $event->getApplication()->getServiceManager();
$config = $serviceManager->get('Config');
$role = $event->getParam($config['new_role_event_param']);
$aclService = $serviceManager->get('CivAccess\AclService');
$aclService->addRole($role, 'user');
}
使用事件系统添加ACL角色的一个警告是,侦听器总是被添加;无论该特定请求中是否需要ACL服务CivAccess\AclService
。
您可以通过将所有上述逻辑移动到创建CivAccess\AclService
的服务 factory 中来避免这种情况。