几周前用这种方法用 Zend 做了一个类似的 REST API:
类变量/常量:
protected $_hasError = false;
const HEADER_APIKEY = 'Authorization';
我的预调度:
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,那么如果发生错误,您的数组将自动返回并显示:
public function init()
{
$contextSwitch = $this->_helper->getHelper('contextSwitch');
$this->_helper->contextSwitch()->initContext('json');
[...]
}
希望这可以帮助