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


ZF2 check if user logged in other modules

伙计们,如果用户已登录或未登录,我该如何检查其他模块?我可以在会话中做到这一点吗?Zend''Auth有更好的方法吗?

我使用Zend''Authentication组件创建了身份验证模块,并且运行良好。

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

  • Auth模块
  • 客户模块
  • 订单模块
  • 管理模块

不,如果用户已登录或未登录,我如何使用我现有的Auth模块签入Admin、Order和Custommer模块?我需要为此创建特定的服务吗?

我不需要和ZF有太多的经验,我正处于学习阶段。

有什么例子和建议吗?

在此处查看我的答案https://stackoverflow.com/a/32392608/949273

$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 Framework 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;
}