laravel 解决 dingo api自定义统一返回格式的方法以及应注意的问题

laravel安装ding go api接口和jwt安装请遵循官方网站:https://github.com/dingo/api/wiki/Installation,
https://github.com/tymondesigns/jwt-auth/wiki/Installation,安装之后按照官方配置就OK了,这里就不再
赘述了。今天写api的时候,遇到api不能统一的问题,这时需要自定义方法去写统一接口方法,当然这边参考
https://github.com/liyu001989/lumen-api-demo这个例子去写,去学习。

  • 介绍下如何去解决接口统一的问题

所有接口更改成下面格式

1
2
3
4
5
6
7
8
9
10
11
12
13
{
"data": {
"username": "ning",
"user_email": "xxx@qq.com",
"register_at": {
"date": "2017-04-04 11:25:13.000000",
"timezone_type": 3,
"timezone": "PRC"
}
},
"status_code": 200,
"message": "success"
}

解决不用数据处理的array数据

加入returnArray 方法,返回上述标准格式

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
<?php
/**
* Created by PhpStorm.
* User: ning
* Date: 2017/3/19
* Time: 下午9:06
*/

namespace App\Api\Controllers;


use App\Http\Controllers\Controller;
use Dingo\Api\Exception\ValidationHttpException;
use Dingo\Api\Routing\Helpers;

class BaseController extends Controller
{
use Helpers;
/**
* @param string $result
* @param int $code
* @param string $message
* @return mixed
* @author ning nkx@ourstu.com
*/
public function returnArray($result = '', $code = 200, $message = 'success')
{
$res = [
'message' => $message,
'status_code' => $code,
'data' => $result
];
return $this->response->array($res)->setStatusCode($code);
}
}

解决item不是标准输出格式

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
public function getAuthenticatedUser()
{
try {

if (!$user = JWTAuth::parseToken()->authenticate()) {
return response()->json(['user_not_found'], 404);
}

} catch (\Tymon\JWTAuth\Exceptions\TokenExpiredException $e) {

return response()->json(['token_expired'], $e->getStatusCode());

} catch (\Tymon\JWTAuth\Exceptions\TokenInvalidException $e) {

return response()->json(['token_invalid'], $e->getStatusCode());

} catch (\Tymon\JWTAuth\Exceptions\JWTException $e) {

return response()->json(['token_absent'], $e->getStatusCode());

}
//调用方式
return $this->response()->item($user, new Usertransform, function ($resource, $fractal) {
$fractal->setSerializer(new CustomSerializer());
});

解决collection不是标准输出格式

1
2
3
4
5
6
7
public function getUsers()
{
//调用方式
return $this->response()->collection(User::all(), new Usertransform, function ($resource, $fractal) {
$fractal->setSerializer(new CustomSerializer());
});
}

上述调用方式的CustomSerializer类

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
<?php
/**
* Created by PhpStorm.
* User: ning
* Date: 2017/5/2
* Time: 下午5:21
*/

namespace App\Api\Serializer;


use League\Fractal\Serializer\ArraySerializer;

class CustomSerializer extends ArraySerializer
{
public function collection($resourceKey, array $data)

{
return ['data' => $data,'status_code'=>200,'message'=>'success'];
}
public function item($resourceKey, array $data)

{
return ['data' => $data,'status_code'=>200,'message'=>'success'];
}
}

另外特别强调下item和collection的区别

collection 第一个参数必须是Collection 对象也就是必须要转换一下,不转换会报错:
“Argument 1 passed to Dingo\Api\Http\Response\Factory::collection() must be an instance of
Illuminate\Support\Collection, instance of App\User given, called in /Volumes/macdata/www/zhihu/
app/Api/Controllers/AuthController.php on line 100 and defined,用 Collection::make($data),这时如果不想
转换,那么直接使用item方法或者使用returnArray方法是明智的,比如上述getAuthenticatedUser()方法,由于JWTAuth返回的用户信息是USER对象,转换成
Collection也会报错: “message”: “get_class() expects parameter 1 to be object, integer given”。用于这个原因
我找了好久文档,希望大家不要犯同样的错误!

感谢老板!