阿东的笔记_  工具
## Yii返回指定格式的RESTful json - 期望的返回格式,同时自动转换需要的内容 ``` json { "code":0, "msg":"OK", // 自动封装code 和 msg "data":[] // yii return 的内容赋值给data } ``` #### 新增 backend\extensions\ResBeforeSendBehavior.php 继承自Behavior ``` php namespace backend\extensions; use Yii; use yii\web\Response; use yii\base\Behavior; use common\models\Users; class ResBeforeSendBehavior extends Behavior{ public $defaultCode = 500; public $defaultMsg = 'error'; // 重载events() 使得在事件触发时,调用行为中的一些方法 public function events() { // 在 EVENT_BEFORE_SEND 事件触发时,调用成员函数 beforeSend return [ Response::EVENT_BEFORE_SEND => 'beforeSend', ]; } public function beforeSend($event) { $response = $event->sender; $status = $response->getStatusCode(); $response->data = [ 'code' => $status == 200 ? 0 : $status , 'data' => $response->data, 'msg' => $response->statusText ]; $response->format = yii\web\Response::FORMAT_JSON; return true; } } ``` #### 新增 backend\components\Exception.php 处理异常响应 ``` php namespace backend\components; use yii\web\ErrorHandler; use common\models\Users; class Exception extends ErrorHandler { /** * 重写渲染异常页面方法 * @param type $exception */ public function renderException($exception) { $code = $exception->getCode(); if( intval($code) == 0 ){ $code = 500; } $data = [ 'code' => $code, 'msg' => $exception->getMessage() //'callback' =>$_GET['callback'], ]; $data['data'] = []; if(YII_DEBUG){ $data['data'] = [ 'file' => $exception->getFile(), 'line' => $exception->getLine(), 'trace' => $exception->getTraceAsString() ]; } header('Content-Type: application/json; charset=utf-8'); echo json_encode( $data , JSON_UNESCAPED_UNICODE ); //header('Content-Type: application/javascript; charset=utf-8');//for jsonp //echo $_GET['callback'].'('.json_encode($data).')'; die; } } ``` #### 在 backend/config/main.php中增加配置,修改errorHandler和response,设置为自定义的类处理响应 ``` php ... 'errorHandler' => [ 'errorAction' => 'site/error', 'class' => 'backend\components\Exception' ], ... 'response' => [ 'class' => 'yii\web\Response', 'as resBeforeSend' => [ 'class' => 'backend\extensions\ResBeforeSendBehavior', ], ], ... ``` #### 完成,这样响应就会自动封装格式,异常也能响应一样的格式
adddge@sohu.com  | 桂ICP备2022009838号-2