The first parameter of the SharedEventManager::attach()
is the identity of the event manager to target. This identity is dynamically assigned for any class that is event capable (implements Zend\EventManager\EventManagerAwareInterface
) or has otherwise had it's identity set via $eventManager->setIdentity()
.
The question refers to the \Zend\Mvc\Controller\AbstractActionController
; this itself is an identity given to any controller that extends \Zend\Mvc\AbstractActionController
(among others), allowing for just one id to attach()
to target all controllers.
To target just one controller (which is perfectly valid, there are many use cases), you can do so in two ways:
- via the
SharedEventManager
, external to the controller class (as you have been doing)
- directly fetching said controller's event manager and handling the events within the controller class.
via SharedEventManager
Use the fully qualified class name as this is is added as an identity to the event manager
$sharedEventManager->attach(
'MyModule\Controller\FooController', 'dispatch', function($e){
});
Within controller
I modify the normal attachDefaultListeners()
method (which is called automatically), this is where you can attach events directly.
namespace MyModule\Controller;
use Zend\Mvc\Controller\AbstractActionController;
use Zend\EventManager\EventInterface;
class FooController extends AbstractActionController
{
protected function attachDefaultListeners()
{
parent::attachDefaultListeners();
$this->getEventManager()->attach('dispatch', array($this, 'doSomeWork'));
}
public function doSomeWork(EventInterface $event) {
}
}