gpt4 book ai didi

zend-framework2 - Zend Framework 2,模块重定向

转载 作者:行者123 更新时间:2023-12-01 20:26:06 24 4
gpt4 key购买 nike

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

最佳答案

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

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

话虽如此,您可能需要重新考虑使用原始 session 。示例(假设您已配置自定义 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-framework2 - Zend Framework 2,模块重定向,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13317037/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com