API 资源和 API 资源集合的辅助修改
前几日询问了关于api资源的一些鸡肋的询问,貌似并未得到有价值的结果。以下是链接:
问答:大家有没有觉得 API 资源和 API 资源集合是鸡肋一样的存在
本来算放弃,只用最原始的函数封装的办法来做呢,但是每每想到这里,心里总是有个梗。于是,经过昨晚的认真分析。写出来下面两个关于资源的类的方法。一个是api资源,一个是api资源类。
实现的主要功能
1、api资源和api资源集合的元数据返回值的封装
2、api资源和api资源集合的输出的数据筛选
筛选提供两种方式,选择和排除。
此举仅仅是抛砖引玉之作,还有大家积极贡献自己的好办法。
api资源
namespace App\Http\Resources;
use Illuminate\Http\Resources\Json\JsonResource;
class CourseResource extends JsonResource
{
// 定义符合的字段的输出列表
protected $only = ['id', 'title', 'price'];
// 定义需要排除的字段列表
protected $except = ['deleted_at', 'created_at', 'updated_at'];
/**
* Transform the resource into an array.
*
* @param \Illuminate\Http\Request $request
* @return array
*/
public function toArray($request)
{
return resource_data($this->selectField($this->resource, 'only'));
}
/*
* 处理字段的筛选符合的内容
* 如果是数组需要对字段帅选的话 可以这么用
*/
private function selectField($data, $type){
// 选择合适结果集
$field = $this->$type;
// 使用字段筛选出符合的字段
return collect($data)->$type($field);
}
}
api资源集合
namespace App\Http\Resources;
use Illuminate\Http\Resources\Json\ResourceCollection;
class CourseCollection extends ResourceCollection
{
// 定义符合的字段的输出列表
protected $only = ['id', 'title', 'price'];
// 定义需要排除的字段列表
protected $except = ['deleted_at', 'created_at', 'updated_at'];
/**
* Transform the resource collection into an array.
*
* @param \Illuminate\Http\Request $request
* @return array
*/
public function toArray($request)
{
// 对返回值记性帅选处理
return resource_data($this->selectField($this->collection, 'except'));
}
/*
* 处理字段的筛选符合的内容
* 如果是数组需要对字段帅选的话 可以这么用
*/
private function selectField($data, $type){
// 对数组进行循环的处理
$field = $this->$type;
return $data->map(function($item) use($type, $field){
return collect($item)->$type($field);
});
}
}
api返回方法封装
/*
* 设置固定的返回值的格式
* $data 为返回的数据
* $code 为返回的状态码
* $msg 为返回的信息
* $jsonp 是否设置为跨域访问
*/
function resource_data($data=[], $code=200, $msg='success'){
return [
'code' => $code,
'msg' => $msg,
'data' => $data
];
}
本作品采用《CC 协议》,转载必须注明作者和本文链接
推荐文章: