0

是否可以重定向到 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);
}
4

1 回答 1

1

这不是你想要在你的layout.phtml. 通常,您希望连接到在渲染之前发生的事件。在 ZF2 中,最早挂钩这类东西的事件是路由事件。Authorization-Module BjyAuthorize中使用的流程示意图很好地解释了这一点:

授权-工作流 BjyAuthorize

如果您不想使用该模块,您也可以缩小那里发生的事情,如下所示:

//class Module
public function onBootstrap(MvcEvent $mvcEvent) 
{
    $eventManager = $mvcEvent->getApplication()->getEventManager();
    $eventManager->attach(MvcEvent::EVENT_ROUTE, array($this, 'onRoute'), -1000);
}

public function onRoute(MvcEvent $event) 
{
    $serviceLocator = $mvcEvent->getApplication()->getServiceLocator();
    // From this point onwards you have access to the ServiceLocator and can check
    // for an authenticated user and if the user is not logged in, you return a 
    // Response object with the appropriate ResponseCode redirected and that's it :)
}
于 2013-08-20T16:07:28.677 回答