$moduleManager->getEventManager()->getSharedManage

2019-07-24 03:20发布

问题:

namespace Auth;

use Zend\ModuleManager\ModuleManager;

class Module
{
    public function init(ModuleManager $moduleManager)
    {
        $sharedEvents = $moduleManager->getEventManager()->getSharedManager();
        $sharedEvents->attach(__NAMESPACE__, 'dispatch', function($e) {
               echo "I am init module dispatch";
               exit();
        }, 100);
    }
}

$moduleManager->getEventManager()->getSharedManager()->attach() is working fine in ZF2 BETA5 but it is not working in stable final release.

Has this functionality taken off in final release?
How can I make this work in ZF2 final release?

回答1:

public function onBootstrap(MvcEvent $e)
{
    $application   = $e->getApplication();
    $sharedManager = $application->getEventManager()->getSharedManager();

    $sharedEvents->attach(__NAMESPACE__, 'dispatch', function($e) {
           echo "I am init module dispatch";
           exit();
    }, 100);
}


回答2:

In Beta Series of zend framework2

Auth\src\User\Controller\UserController.php

but in final release of zf2 this does not work. Main namespace folder should match exactly same as under src folder. so above will work only like this

Auth\src\Auth\Controller\UserController.php
or
User\src\User\Controller\UserController.php

Don't forget to change your namespaces and paths in module.php and module.config.php and controller file.



回答3:

There are two ways,

You can get it from Module.php init method, by passing ModuleManger object into it and then modulemanager->getEventManager.

Or from onBootstrap method again in Module.php but not from ModuleManager but by the application object as Abdul did.

Remember, init and onBoostrap methods run for every page request. Registering Event there is okay but do not put heavy stuff there. I prefer sharedEventManager, as it is available even if the service is initializes in future.

Cheers!