Zend 2 redirect() 模块错误

Zend 2 redirect() module error

我已经创建了检查登录功能来检查 $auth->getIdentity(), 但我收到以下错误:

Fatal error: Call to undefined method Admin\Module::redirect() in C:\xampp\websites\zend2\module\Admin\Module.php on line 51

我该如何解决这个问题?

public function onBootstrap(MvcEvent $e)
{

    $eventManager        = $e->getApplication()->getEventManager();
    $moduleRouteListener = new ModuleRouteListener();
    $moduleRouteListener->attach($eventManager);
    $app = $e->getParam('application');
    $app->getEventManager()->attach('render', array($this, 'setLayoutTitle'));

    $moduleRouteListener->attach($eventManager);

    // add event
    $eventManager->attach('render', array($this, 'checklogin')); 


}


public function checkLogin()
{   
    $auth = new AuthenticationService();
    if( $auth->getIdentity() == NULL ){
        return $this->redirect()->toRoute('/admin/login');  
    }else{
       return $this->redirect()->toRoute('/admin'); 
    }
}

那是因为Moduleclass中没有redirect方法。

我建议在 dispatch 事件中移动此检查,因为 dispatch 事件在 控制器动作被调度之前 被触发。

所以需要在onBootstrap模块方法中修改监听方法设置:

public function onBootstrap(MvcEvent $e)
{
    // ...
    $eventManager->attach(MvcEvent::EVENT_DISPATCH, array($this, 'checkLogin'));
    // ...
}

然后在侦听器方法中你得到 MvcEvent 其中 target 匹配控制器 class:

public function checkLogin(MvcEvent $e)
{
    $controller = $e->getTarget();
    if ($someCondition) {
        return $controller->plugin('redirect')->toRoute('your/route/name');
    }
}
public function onBootstrap(MvcEvent $e)
{

    $eventManager        = $e->getApplication()->getEventManager();
    $moduleRouteListener = new ModuleRouteListener();
    $moduleRouteListener->attach($eventManager);
    $app = $e->getParam('application');
    $app->getEventManager()->attach('render', array($this, 'setLayoutTitle'));
    $eventManager->attach(MvcEvent::EVENT_DISPATCH, array($this, 'checkLogin'));
}

public function checkLogin(MvcEvent $e)
{
    $iden = new AuthenticationService();
    if( $iden->getIdentity() === NULL ){
        $matches    = $e->getRouteMatch();
        $controller = $matches->getParam('controller');
        $getController = explode( '\', $controller );      
    if( $getController[2] != 'Login' ){
        $controller = $e->getTarget();
        return $controller->plugin('redirect')->toRoute('login');
    }
}