ZF2: Attach event to another Controller's Acti

2019-09-03 03:55发布

问题:

I am new to Zend Framework 2. I have two modules 'A' and 'B'. I trigger an event in LoginController's LoginAction of "A" module. I want to attach LoginController's LoginAction or LoginController's testMe() method.

In "A" module's LoginController's LoginAction, I have written

$this->getEventManager()->trigger('checkme.post', null, array('user_id' => $userData->usydstudentid));

In Module.php of "B" module, in on Bootstrap method, I have given

$loginController = new B\Controller\LoginController();

$sharedEventManager->attach('A\Controller\LoginController', 'checkme.post', array($loginController, 'LoginAction'), 100); 

In LoginController's LoginAction of "B" module, I can access data but I can not access service manager in order to get module' config. When I try to use

$this->getServiceLocator()->get('Config');

I get error

Call to a member function get() on a non-object

In other words, I want to trigger an event from one controller's method and attach to another controller's method. After listening, getting data from that event, I want to get module's config. Please help in this regard.

回答1:

First of all, you shouldn't use events and controllers this way. Your controller from B isn't a controller, but you should put that one rather in a service layer.

Then, the service locator must be injected. If you do $controller = new SomeController this service locator is not injected. Thus, fetching any object from it will fail. What you should do is using the controller loader to get the controller.

So instead of this:

$loginController = new B\Controller\LoginController();

$sharedEventManager->attach('A\Controller\LoginController',
                            'checkme.post',
                            array($loginController, 'LoginAction'),
                            100); 

You should write this:

// $sl is instance of Service Locator
// E.g. $sl = $e->getApplication()->getServiceManager();
// Where $e is the event from the onBootstrap() method

$loader          = $sl->get('ControllerLoader');
$loginController = $loader->get('B\Controller\LoginController');

$sharedEventManager->attach('A\Controller\LoginController',
                            'checkme.post',
                            array($loginController, 'LoginAction'),
                            100); 

But as said, triggering an action in a controller this way with events isn't realy a good way to do it. You better dispatch it with for example the controller plugin Forward or (as I said it before), remove the logic from the controller's LoginAction and locate it in a service class or something.