1

如何在控制器构造函数中访问事件管理器?当我在构造函数中调用事件管理器时,出现此错误:

Zend\ServiceManager\ServiceManager::get 无法获取或创建事件实例

4

1 回答 1

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);
}

我只会使用事件来附加你需要的东西,而不是使用控制器

模块.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);
}
于 2013-08-16T08:55:39.310 回答