是否可以重定向到 ZF2 中 Layout.phtml 中的路由。如果用户未从 layout.phtml 登录,我想重定向到登录页面
到目前为止,我已经尝试过:
<?php $auth = new AuthenticationService();
if ($auth->hasIdentity()) {?>
<li class="active"><a href="<?php echo $this->url('home') ?>">
<?php echo $this->translate('Home') ?></a></li>
<li class="active"><a href="<?php echo $this->url('login/process', array('action'=>'logout')) ?>"><?php echo $this->translate('Logout') ?></a></li>
<?php
}
else
{
$this->_forward('login/process');
} ?>
它给了我错误“获取无法获取或创建_forward的实例”
引导代码:
public function onBootstrap(MvcEvent $e)
{
$e->getApplication()->getServiceManager()->get('translator');
$eventManager = $e->getApplication()->getEventManager();
$moduleRouteListener = new ModuleRouteListener();
$moduleRouteListener->attach($eventManager);
$eventManager = $e->getApplication()->getEventManager();
//nothing's available for non logged user, so redirect him to login page
$eventManager->attach("dispatch", function($e) {
$match = $e->getRouteMatch();
$list = $this->whitelist;
// Route is whitelisted
$name = $match->getMatchedRouteName();
if (in_array($name, $list)) {
return;
}
$sm = $e->getApplication()->getServiceManager();
$controller = $e->getTarget();
$auth = $sm->get('AuthService');
if (!$auth->hasIdentity() && $e->getRouteMatch()->getMatchedRouteName() !== 'login/process') {
$application = $e->getTarget();
$e->stopPropagation();
$response = $e->getResponse();
$response->setStatusCode(302);
$response->getHeaders()->addHeaderLine('Location', $e->getRouter()->assemble(array(), array('name' => 'login/process')));
//returning response will cause zf2 to stop further dispatch loop
return $response;
}
}, 100);
}