ZF2: Attach event to another Controller's Action and get Service Locator

我只是一个虾纸丫 提交于 2019-12-12 04:59:42

问题


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.



来源:https://stackoverflow.com/questions/19696781/zf2-attach-event-to-another-controllers-action-and-get-service-locator

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!