如何在控制器构造函数中访问事件管理器?当我在构造函数中调用事件管理器时,会出现此错误:
Zend \ ServiceManager \ ServiceManager :: get无法获取或创建事件实例
答案 0 :(得分:2)
此时您无权访问服务管理器,因为一旦对象被实例化,它就会被注入。
您总是可以将代码移动到onDispatch()而不是在构造函数中触发:
/**
* Execute the request
*
* @param MvcEvent $e
* @return mixed
* @throws Exception\DomainException
*/
public function onDispatch(MvcEvent $e)
{
// do something here
// or you could use the events system to attach to the onDispatch event
// rather than putting your code directly into the controller, which would be
// a better option
return parent::onDispatch($e);
}
我只是使用事件来附加你需要的东西,而不是使用控制器
Module.php
/**
* Initialize
*
* @param \Mis\ModuleManager
*/
public function init(ModuleManager $manager)
{
$events = $manager->getEventManager();
$sharedEvents = $events->getSharedManager();
$sharedEvents->attach(__NAMESPACE__, 'dispatch', function($e) {
/* @var $e \Zend\Mvc\MvcEvent */
// fired when an ActionController under the namespace is dispatched.
$controller = $e->getTarget();
$routeMatch = $e->getRouteMatch();
/* @var $routeMatch \Zend\Mvc\Router\RouteMatch */
$routeName = $routeMatch->getMatchedRouteName();
// Attach a method here to do what you need
}, 100);
}