2

我的 module.php 中有一个函数,它在其他所有内容开始加载之前被调用,它验证用户是否已登录,但如果用户未登录,我需要它重定向到登录页面,我可以只使用“标题”,但我想学习“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!!!!!
    }
}
4

1 回答 1

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;

话虽如此,您可能需要重新考虑使用原始会话。示例(假设您已配置自定义 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;

}
于 2012-11-10T00:12:25.657 回答