以下是 laravel 版本,增加了 headers
OutFormatTrait.php
<?php
/**
* 格式化输出数据
*
* Class outFormat
* @package App\Sanjieke\Logic
*/
trait OutFormatTrait
{
protected static $http_200 = 200;
protected static $default_headers = [
'Content-Type' => 'application/json; charset=UTF-8'
];
/**
* 成功,返回数据
* @param array $data
* @param string|array $msg
* @return \Illuminate\Http\JsonResponse
*/
protected function successOutDataMsg(array $data, $msg = 'ok')
{
return $this->outFormat(self::$http_200, $data, $msg);
}
/**
* 成功只返回提示信息
* @param string $msg
* @return \Illuminate\Http\JsonResponse
*/
protected function successOutMsg($msg = 'ok')
{
return $this->outFormat(self::$http_200, [], $msg);
}
/**
* 返回错误 code 及 信息
*
* @param int $code
* @param string|array $msg
* @param array $data
* @return \Illuminate\Http\JsonResponse
*/
protected function errorOutFormat($code, $msg = '有点问题,请稍后重试', array $data = [])
{
return $this->outFormat($code, $data, $msg);
}
/**
* 统一格式输出
*
* @param int $code
* @param array|string $data
* @param string|array $msg
* @param array $headers
* @param int $options
* @return \Illuminate\Http\JsonResponse
*/
protected function outFormat($code, $data, $msg, array $headers = [], $options = JSON_UNESCAPED_UNICODE)
{
return response()->json([
'code' => $code,
'data' => $data,
'msg' => $msg,
], self::$http_200, array_merge(self::$default_headers, $headers), $options);
}
}