Zend Framework 2,模块重定向 [英] Zend Framework 2, Module Redirect

查看:26
本文介绍了Zend Framework 2,模块重定向的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I have a function in my module.php with the following function which is called before everything else starts to load, it verifies that the user is logged on but I need it to redirect to the login page if the user is not logged in, I could just use "header" but I want to learn the "Zend" way of doing things.

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!!!!!
    }
}

推荐答案

这正是您要问的问题:

        //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;

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

That being said, you might want to reconsider using the raw session. Example (assumes you've configured a custom 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;

}

这篇关于Zend Framework 2,模块重定向的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆