我正在ZF2上实现REST API。现在我需要检查模块上的授权令牌.php如果授权失败,则返回错误。但是我不知道如何从模块返回响应.php。
我编写了代码来检查onBootstrap的DISPATCH事件中的授权。现在如何从模块返回错误.php如果授权失败而不访问控制器。由于只有exit
函数/调用才能在不访问控制器的情况下返回。但在这种情况下,我没有得到任何回应。使用json_encode(数组)看起来不像标准,因为我已经启用了ViewJsonStrategy并在控制器中使用JsonModel。
您可以通过让侦听器返回响应来缩短事件,例如...
public function onBootstrap(EventInterface $e)
{
$eventManager = $e->getApplication()->getEventManager();
// attach dispatch listener
$eventManager->attach('dispatch', function($e) {
// do your auth checks...
if (!$allowed) {
// get response from event
$response = $e->getResponse();
// set status 403 (forbidden)
$response->setStatusCode(403);
// shortcircuit by returning response
return $response;
}
});
}