Php Yii框架控制器包装器

Php Yii框架控制器包装器,php,rest,yii,Php,Rest,Yii,我正在尝试使用yii设置一个restfulapi。尝试添加一个包装器,该包装器获取在控制器中运行的代码的结果,并以json格式返回。我还试图让它捕获任何错误[try catch],并以json格式返回它们 现在我所能想到的就是做一些类似于下面代码的事情……我希望不必每次都添加try/catch class UserController extends Controller{ public function actionIndex($user_id = null){ $r

我正在尝试使用yii设置一个restfulapi。尝试添加一个包装器,该包装器获取在控制器中运行的代码的结果,并以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-catch

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();
    }
}