shadowm2 / coke
此包最新版本(0.02)没有可用的许可信息。
数据源与输出之间的层
0.02
2018-08-07 06:54 UTC
Requires
- php: >=5.3.0
This package is not auto-updated.
Last update: 2024-09-26 16:57:07 UTC
README
安装(Lumen)
$ composer require shadowm2/coke
在您的bootstrap/app.php中添加此行
$app->register(Shadow\Coke\CokeServiceProvider::class);
使用此别名以获得更多舒适。在您的bootstrap/app.php中添加此行
class_alias(\Shadow\Coke\Facades\Coke::class, 'Coke');
用法
在模型中定义一个名为"transform"的函数。
class User .... {
...
function transform()
{
return [
'name' => $this->name,
'token' => "dummy"
];
}
}
然后您可以像这样使用Coke
use Coke;
$user = User::first();
$response = Coke::transform($user);
return $response;
// Output : {"name": "sth", "token": "dummy"}
Coke的输入必须以这种形式
Coke::tranform($data): $data must be Collection|Model|LengthAwarePaginator
如果您想在模型上使用另一个transform函数,并且一个模型有多个transform函数,请按照以下方式传递另一个参数
$changes = [
'App\User' => 'anotherFunction' // keys in this array are path to your models
];
Coke::transform($user, $changes);
添加关系非常简单。您应该在查询中添加您的关联,并在每个使用的模型中定义transform函数。
$data = User::first()->posts()->where('post_type', 2)->get();
$response = Coke::transform($data);
/*
* Output: {'name': 'sth', 'token': 'dummy', 'posts': [{
* ...
* }]}
*
*/
在这个例子中,posts是一个hasMany关系,所以每个帖子都是单独转换的。
分页也受到支持。
$users = User::paginate();
return Coke::Transform($users);