我有一个配置json策略的webservice模块。我正在做一个登录功能,如果用户没有登录返回一个错误。
要测试用户是否已登录,请在模块类
上设置事件调度。class Module {
public function onBootstrap(MvcEvent $e) {
(...)
$eventManager->attach(MvcEvent::EVENT_DISPATCH, array($this, 'mvcPreDispatch'), 1000);
}
public function mvcPreDispatch(MvcEvent $e) {
$authService = $e->getApplication()->getServiceManager()->get('auth');
if($authService->isAuthenticated()) {
return true;
}
$model = new JsonModel(array(
'errors' => array(
'httpCode' => $e->getResponse()->getStatusCode(),
'title' => $e->getResponse()->getReasonPhrase(),
'message' => 'Login necessário'
)
));
return $model;
}
}
如何停止请求并在屏幕上显示错误信息?
您可能需要通过返回Response
对象或在事件上调用stopPropagation(true)
来短路事件。这将阻止所有其他调度侦听器的执行,并向客户端返回一个响应。
你可以尝试这样做:
public function mvcPreDispatch(MvcEvent $e)
{
$authService = $e->getApplication()->getServiceManager()->get('auth');
if($authService->isAuthenticated()) {
return true;
}
$model = new JsonModel(array(
'errors' => array(
'httpCode' => $e->getResponse()->getStatusCode(),
'title' => $e->getResponse()->getReasonPhrase(),
'message' => 'Login necessário'
)
));
$e->setViewModel($model);
$e->stopPropagation(true);
}