LaravelRestify是一个包,用Laravel制作一个强大的JSON:API兼容的Rest API。在安装了这个包并按照设置指南,你可以快速开始使用资源库CLI。
php artisan restify:repository Dream --all
存储库是这个包的核心.上面的例子命令会生成一个空白的版本库,你可以在上面添加字段,就像下面的例子。
namespace App\Restify;
use App\Models\Dream;
use Binaryk\LaravelRestify\Http\Requests\RestifyRequest;
class DreamRepository extends Repository
{
public static string $model = Dream::class;
public function fields(RestifyRequest $request): array
{
return [
id(),
field('title')->required(),
field('description'),
field('image')->image(),
];
}
}
如果你没有定义$model 属性,Restify 可以根据版本库的类名来猜测(即DreamRepository 将是Dream 模型)。
下面是一个内置的UserRepository 类的例子(你会想在真正的应用中保护这个),它将以JSON API格式返回一个API响应。
GET: /api/restify/users?perPage=10&page=2
{
"meta": {
"current_page": 1,
"from": 1,
"last_page": 1,
"path": "http://localhost:8000/api/restify/users",
"per_page": 15,
"to": 1,
"total": 1
},
"links": {
"first": "http://localhost:8000/api/restify/users?page=1",
"next": null,
"path": "http://localhost:8000/api/restify/users",
"prev": null,
"filters": "/api/restify/users/filters"
},
"data": [
{
"id": "1",
"type": "users",
"attributes": {
"name": "Paul Redmond",
"email": "paul@example.com"
}
}
]
}
这个包还会引导你完成认证过程、高级过滤以及更多的工作