1

Zend Framework 1.12 を使用して REST API を作成しています。コントローラープラグインの「Authorization」ヘッダーを確認したい。

プラグインの preDispatch アクションにコードを入れました

$authorizationHeader    =   $request->getHeader('Authorization');
if(empty($authorizationHeader)) {
    $this->getResponse()->setHttpResponseCode(400);
    $this->getResponse()->setBody('Hello');
    die(); //It doesn't work
}

問題は、コントローラーのアクションがまだ呼び出されていることです。「die()」、「exit」を試しました。私の質問は、プラグインから応答を返し、コントローラーのアクションを呼び出さない方法です。

4

2 に答える 2

2

このアプローチで、数週間前に 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');

    [...]

}

お役に立てれば

于 2013-08-06T07:25:15.577 に答える