【问题标题】:ZF2 How to access event manager in controller's constructorZF2 如何在控制器的构造函数中访问事件管理器
【发布时间】:2013-08-16 16:55:39
【问题描述】:

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

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

【问题讨论】:

    标签: constructor controller zend-framework2


    【解决方案1】:

    此时您无权访问服务管理器,因为它是在对象被实例化后注入的。

    您可以随时移动代码以触发 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);
    }
    

    【讨论】:

    • 尽管答案的年龄,我想知道,一旦你在 module.php 的// Attach a method here to do what you need 使用方法完成了一些工作,如何让结果/数据通过到目标控制器?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2010-11-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多