Zend framework2 Zend框架2,模块重定向
我在module.php中有一个函数,在其他所有内容开始加载之前调用该函数,它验证用户是否已登录,但我需要它重定向到登录页面。如果用户未登录,我可以使用“header”,但我想学习“Zend”方式Zend framework2 Zend框架2,模块重定向,zend-framework2,Zend Framework2,我在module.php中有一个函数,在其他所有内容开始加载之前调用该函数,它验证用户是否已登录,但我需要它重定向到登录页面。如果用户未登录,我可以使用“header”,但我想学习“Zend”方式 public function preDispatch($e) { if (!isset($_SESSION)) session_start(); $sm = $e->getApplication()->getServiceManager(); $adapters
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!!!!!
}
}
公共职能预分配($e)
{
如果(!isset($_SESSION))SESSION_start();
$sm=$e->getApplication()->getServiceManager();
$adapters=$sm->get('dbAdapters');
如果(!isset($_会话['auth'])$_会话['auth']=new MyAuth($adapters[1]);
如果($\会话['auth']->IsValid())
{
回显“有效
”;
}
其他的
{
$e->getControllerClass()->redirect()->toRoute('login-success');
回显“!有效
”;
//重定向到此处的登录页面!!!!!
}
}
这正是您要问的问题:
//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):
我遇到了这个错误,我尝试包含必要的文件但没有成功,调用了未定义的方法Zend\Mvc\Application::plugin()
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;
}