做过类似REST API与Zend几个星期前使用这种方法:
类瓦尔/ Consts:
protected $_hasError = false;
const HEADER_APIKEY = 'Authorization';
我preDispatch:
public function preDispatch()
{
$this->_apiKey = ($this->getRequest()->getHeader(self::HEADER_APIKEY) ? $this->getRequest()->getHeader(self::HEADER_APIKEY) : null);
if (empty($this->_apiKey)) {
return $this->setError(sprintf('Authentication required!'), 401);
}
[...]
}
我定制SETERROR功能:
private function setError($msg, $code) {
$this->getResponse()->setHttpResponseCode($code);
$this->view->error = array('code' => $code, 'message' => $msg);
$this->_hasError = true;
return false;
}
然后,只需检查是否有错误已设置你的函数中:
public function yourAction()
{
if(!$this->_hasError) {
//do stuff
}
}
如果您使用ContextSwitch里和JSON,然后用你的错误阵列将自动返回&显示,如果有错误occours:
public function init()
{
$contextSwitch = $this->_helper->getHelper('contextSwitch');
$this->_helper->contextSwitch()->initContext('json');
[...]
}
希望这有助于
感谢详细的答复。所以,如果在每个api动作中检查这个条件(!$ this - > _ hasError)吗?我宁愿直接从插件重定向。 – Tamara
即使认证错误发生,我也使用此解决方案来输出其他数据/信息。如果你不想检查每个动作,只需将'setError'函数中的第3行更改为'抛出新的Zend_Exception($ code,$ msg)' – simplyray
好的,谢谢。此外,我想我可以抛出一些自定义异常来区分REST API异常与其他错误控制器中的异常。 – Tamara