Laravel 响应优化

Laravel 响应优化

创建一个助手函数文件,记得在 composer.json 里面引入且重新加载,这东西真的很方便,哈哈哈。

这里的优化不是万能的,也一些场景是不考虑的,需要执行进行处理,比如 401 登陆。

app\helpers.php

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
<?php

if(!function_exists('result')) {
/**
* 返回数据
*
* @param string|array $data 数据
* @param int $status 状态码
* @return \Illuminate\Http\Response
*/
function result($data = null, int $status = 200) {
return response()->json(
is_null($data) ? ['code' => 1] : ['code' => 1, 'data' => $data],
$status
);
}
}

if(!function_exists('error')) {
/**
* 返回错误
*
* @param string $msg 错误信息
* @param int $status 状态码
* @return \Illuminate\Http\Response
*/
function error(string $msg = '参数错误', int $status = 200) {
return response()->json(
['code' => 0, 'message' => $msg],
$status
);
}
}

这个是重点了,创建中间件文件。

1
$ php artisan make:middleware Response

app\Http\Middleware\Response.php

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
<?php

namespace App\Http\Middleware;

use Closure;

class Response
{
/**
* Handle an incoming request.
*
* @param \Illuminate\Http\Request $request
* @param \Closure $next
* @return mixed
*/
public function handle($request, Closure $next)
{
$response = $next($request);

// HTTP 状态码非 200 的进行跳过
if(!$response->isOk()) {
return $response;
}

// 获取原始内容
$content = $response->original;

if(is_string($content)) {
return error($content);
} else if($content instanceof \Illuminate\Contracts\Support\Arrayable) {
return result($content->toArray());
} else if(is_array($content)) {
return result($content);
}

return $response;
}
}

对中间件进行全局注册,由于我这边都是前后分离的模式,所以我在 $middleware 注册即可;如果你不是的话需要放在 $middlewareGroups 里面注册,避免影响到了其他。

app\Http\Kernel.php

1
2
3
4
protected $middleware = [
...
\App\Http\Middleware\Response::class,
];

又是测试环节。。。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
public function index()
{
return '参数错误';
// {"code":0,"message":"参数错误"}

// return Banner::get();
// {"code":1,"data":[{"id":1,"images":"https://cdn.hongfs.cn/1.png"}]}

// return [];
// {"code":1,"data":[]}

// return error('请重新登录', 401);
// HTTP 状态码 401
// {"code":0,"message":"请重新登录"}
}
往上