【问题标题】:Zend Framework 2 dispatch event doesn't run before actionZend Framework 2 调度事件在动作之前不运行
【发布时间】:2013-10-28 15:34:44
【问题描述】:


我需要帮助。我想在控制器的动作运行之前在 Zend Framework 2 中运行一个方法。我将我的方法放在 Module.php 的 onBootstrap 中,但它在操作启动之前没有运行。

在 Module.php 中:

public function onBootstrap(MvcEvent $e)
{
    $eventManager        = $e->getApplication()->getEventManager();
    $moduleRouteListener = new ModuleRouteListener();
    $moduleRouteListener->attach($eventManager);

    $app  = $e->getApplication();
    $em = $app->getEventManager();

    $em->attach(MvcEvent::EVENT_DISPATCH, function($e) {
        $controller = $e->getTarget();
        $controller->Init();
    });
}

我想对我的适配器运行 Init() 方法,它将在操作运行之前初始化,但它不起作用,我总是收到以下消息:
可捕获的致命错误:参数 1 传递给 Application\ Model\Members::__construct() 必须是 Zend\Db\Adapter\Adapter 的实例,给定 null,在第 39 行的 PATH\module\Application\src\Application\Controller\AdminController.php 中调用并在 PATH\module 中定义\Application\src\Application\Model\Members.php 第 17 行

成员类在应该运行的动作中,它的 __construct 需要有一个有效的 Adapter 对象,应该在 Init() 方法中初始化。

谁能帮帮我? 非常感谢!

【问题讨论】:

    标签: php zend-framework2


    【解决方案1】:

    尝试不同的方法:

    我假设您的控制器扩展了 Zend\Mvc\Controller\AbstractActionController。在您的控制器中覆盖父级的 onDispatch 方法,以执行您需要执行的操作:

    例如:

    class YourController extends AbstractActionController {
    
        public function onDispatch($event){
            $this->Init();
            return parent::onDispatch($event);
        }
        //your other actions/init methods etc...
    
    }
    

    【讨论】:

      【解决方案2】:

      附加到事件时需要设置优先级> 1。

      例如。

      $em->attach(MvcEvent::EVENT_DISPATCH, function($e) {
              $controller = $e->getTarget();
              $controller->Init();
          }, 100);
      

      这确保代码在调度前执行。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2013-01-21
        • 2014-01-22
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多