Zend Framework 2,模块重定向

ros*_*lin 2 zend-framework2

我在我的module.php中有一个函数,它具有以下函数,在其他所有开始加载之前调用它,它验证用户是否已登录,但如果用户未登录,我需要它重定向到登录页面,I可以只使用"标题",但我想学习"Zend"的做事方式.

public function preDispatch($e)
{
    if (!isset($_SESSION)) session_start();

    $sm = $e->getApplication()->getServiceManager();
    $adapters = $sm->get('dbAdapters');
    if (!isset($_SESSION['auth'])) $_SESSION['auth'] = new MyAuth($adapters[1]);

    if ($_SESSION['auth']->IsValid())
    {
        echo 'Valid<br />';
    }
    else
    {
        $e->getControllerClass()->redirect()->toRoute('login-success');
        echo '!Valid<br />';
        //REDIRECT TO LOGIN PAGE HERE!!!!!
    }
}
Run Code Online (Sandbox Code Playgroud)

dua*_*mon 8

这是您所询问的具体内容:

        //REDIRECT TO LOGIN PAGE HERE!!!!!

        /**
         * grab Controller instance from event and use the native redirect plugin
         */
        $controller = $e->getTarget();
        $controller->plugin('redirect')->toUrl('/logout?' . $query);

        /**
         * optionally stop event propagation and return FALSE
         */
        $e->stopPropagation();
        return FALSE;
Run Code Online (Sandbox Code Playgroud)

话虽如此,您可能想重新考虑使用原始会话.示例(假设您已配置自定义authAdapter):

public function checkSession($e)
{
    $controller = $e->getTarget(); // grab Controller instance from event

    $app          = $e->getApplication();
    $locator      = $app->getServiceManager();
    if ($controller instanceof LogoutController) return;
    $authService = $locator->get('ds_auth_service');
    $authAdapter = $locator->get('ds_auth_adapter');

    /*
     * try to authenticate
     */
    if (!$authService->hasIdentity()){
        $result = $authService->authenticate($authAdapter);
        if ($authService->hasIdentity()) {
            $this->getEventManager()->trigger('authenticate', $this, array('result' => $result));
        }
    }

    /*
     * If we are not in an exempt controller and no valid identity, redirect
     */
    $isExempt = $controller instanceof \Application\Controller\LogoutController;
    if (!$isExempt && !$authService->hasIdentity()) {
        $query = http_build_query($result->getMessages());
        $controller->plugin('redirect')->toUrl('/logout?' . $query);
        $e->stopPropagation();
        return FALSE;
    }

    // User is logged in
    return TRUE;

}
Run Code Online (Sandbox Code Playgroud)