做過類似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