Laravel5设计json api时候的一些道道
2015-04-14 08:13
316 查看
对于返回数据格式没规整的问题
在开发api的时候,这个问题是和客户端交涉最多的问题,比如一个user结构,返回的字段原本是个user_name的,它应该是string类型。但是呢,由于数据库设计这个字段的时候允许为null,那么这个字段获取回来,就可能返回null,这个对于弱类型语言是没什么问题的,但是对于强类型的语言,可能就要增加字符的类型判断了。或者是数据库中的text字段,里面存放的是json数据,现在取出来的时候我要做一些转换等。
所以对这个问题,我们会想到做一个类的格式方法。这个方法自然就是写在model中,在laravel5中,我使用这种方法:
model中:
class Inbox extends Model { protected $table = 'inbox'; public static function format() { return function($item) { $tmp = $item->toArray(); unset($tmp['deleted_at']); $tmp['sort'] = $tmp['id']; $tmp['uid'] = $tmp['sender']; $content = json_decode($item->content, true); $tmp['content'] = json_decode($content['content'], true); return $tmp; }; } public static function formatRaw() { return function($item) { $tmp = $item->toArray(); unset($tmp['deleted_at']); $tmp['sort'] = $tmp['id']; $tmp['uid'] = $tmp['sender']; return $tmp; }; } }
这里的Inbox设计了两种返回格式,每种返回格式都是返回的闭包函数,然后在controller中
$builder = Inbox::where('receiver', $uid)->where('sender', 0); if ($max) { $builder->where('id', '<', $max); } $inboxs = $builder->orderBy('id', 'desc')->get(); $data = $inboxs->transform(Inbox::formatRaw());
好了,这样返回的$data就是进行结构化好的数据了。
这里主要想说laravel的Collection中的transfrom函数太好用了,参数是一个闭包,然后这个闭包封装在model中,好处是一旦客户端想要修改或者更新某个输出字段,我们就可以只要修改format函数就行。
对于返回外带外键的问题
比如上面一个例子中,往往inbox有个uid,接口需要它返回user的信息。那么这个时候,model的foreign key就起到很好的作用class Inbox extends Model { protected $table = 'inbox'; public function user() { return $this->hasOne('User', 'id', 'uid'); } public static function format() { return function($item) { $user = $item->user; $tmp = $item->toArray(); unset($tmp['deleted_at']); $tmp['sort'] = $tmp['id']; $tmp['uid'] = $tmp['sender']; $content = json_decode($item->content, true); $tmp['content'] = json_decode($content['content'], true); $tmp['user'] = $user; return $tmp; }; } }
但是这里切记别让每个数据循环获取user,我们应该显示地使用load或者with:
$builder = Inbox::where('receiver', $uid)->where('sender', 0); if ($max) { $builder->where('id', '<', $max); } $inboxs = $builder->orderBy('id', 'desc')->get(); $inboxs->load('user'); $data = $inboxs->transform(Inbox::formatRaw());
总结
基本将这样两个问题解决,设计好orm,使用laravel来写接口就很快了。相关文章推荐
- Laravel 5 中使用 JWT(Json Web Token) 实现基于API的用户认证
- Laravel 开发 RESTful API 的一些心得
- rails 中 使用 rabl 来生成 json 的时候 ,一些小技巧
- json_encode在设计api时需要注意的问题
- 如何设计出一些优雅的API接口呢?
- API设计的一些心得总结
- Qt刷新机制的一些总结(Qt内部画的时候是相当于画在后台一个对象里,然后在刷新的时候调用bitblt统一画,调用window的api并不会影响到后面的那个对象)
- RESTful API URI 设计的一些总结
- springboot在使用controller返回list集合或json字符串到浏览器的时候不显示字符串,出现一些标签
- Golang 中使用 JSON 的一些小技巧 陶文 陶文 3 个月前 有的时候上游传过来的字段是string类型的,但是我们却想用变成数字来使用。 本来用一个json:",string" 就可以支持了
- 网站设计时候的一些基本原则
- 关于REST API设计的一些小经验
- Microservices中的API设计 - HAL+Json API
- PHP使Laravel为JSON REST API返回自定义错误的问题
- 可以将一些配置信息已json格式存在数据库中读取的时候序列化。
- 使用Httpclient调用API的一些个人见解(返回的json)
- FastJson一些常见方法(API)
- 让Laravel API永远返回JSON格式响应的方法示例
- Dingo + Laravel + JWT + Entrust + memcache 实现API设计
- SpringBoot使用教程【1】Restful API设计 返回json,xml格式