ZF2 检查用户是否登录其他模块

ZF2 check if user logged in other modules

伙计们,如果用户已登录,我该如何检查其他模块?我可以通过会话来做到这一点,还是 Zend\Auth 有更好的方法来做到这一点?

我使用 Zend\Authentication 组件创建了 auth 模块,一切正常。

我想像这样分离我的模块:

不知道我现有的 Auth 模块如何在用户登录或未登录的情况下签入 Admin、Order 和 Custommer 模块?我需要为此创建特定服务吗?

我对ZF没有太多经验,正处于学习阶段。

有什么例子和建议吗?

在这里查看我的回答

$events->attach(MvcEvent::EVENT_ROUTE, __CLASS__ . '::checkPermission', -100);

基本上在我执行的每个请求中

public static function checkPermission(MvcEvent $e)
{
    $auth = $e->getApplication()->getServiceManager()->get('Zend\Authentication\AuthenticationService');

    if(!$auth->hasIdentity()){
        $url      = $e->getRouter()->assemble([], ['name' => 'login']);
        $response = $e->getResponse();
        $response->getHeaders()->addHeaderLine('Location', $url);
        $response->setStatusCode(302);
        $response->sendHeaders();

        return $response;
    }
}

Zend 框架 2

在您的其他控制器中

public function yourAction() {
        $this->_authenticate(); 
        $this->view['identity'] = (array)$this->identity;
        // your code here
}

// authentication function

public function _authenticate() {

    if(!$this->getServiceLocator()->get('AuthService')->hasIdentity()) {
         return $this->redirect()->toRoute('auth');
    } else {
        $this->identity = $this->getServiceLocator()->get('AuthService')->getIdentity();
    }
}

public function getAuthService()  {
    if (! $this->authservice) {
        $this->authservice = $this->getServiceLocator()->get('AuthService');
    }

    return $this->authservice;
}