簡體   English   中英

Yii框架控制器包裝器

[英]Yii framework controller wrapper

我正在嘗試使用yii建立一個寧靜的api。 嘗試添加一個包裝器,以獲取在控制器中運行的代碼的結果並以json格式返回。 我也試圖讓它捕獲任何錯誤[try-catch],並以json格式返回它們。

現在我所能想到的就是與下面的代碼類似的東西...我希望不必每次都添加try / catch的能力。

class UserController extends Controller{

    public function actionIndex($user_id = null){
        $response = new API_Response();

        try{
            $response->success = true;
            $response->data = array("data"=>"data goes here...");
        }catch(Exception $e){
            $response->success = false;
            $response->message = $e->getMessage();
        }

        $response->send();
    }

經過更多的研究,發現我可以覆蓋每個控制器的api處理程序,因此現在不必寫一堆try-catches。

function init(){
    $this->api_resp = new API_Response();
    Yii::app()->attachEventHandler('onException',array($this, 'handleApiError'));
}
public function handleApiError(CEvent $e){
    if($e instanceof CExceptionEvent){
        $this->api_resp->error = $e->exception->getMessage();
        $this->api_resp->send();
    }else{
        $this->api_resp->error = Yii::t('app', 'error.unknown');
        $this->api_resp->send();
    }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM