paulvl / json-api
用于快速实现Laravel 5.1 API的包
Requires
- php: >=5.5.9
- laravel/framework: 5.1.*
- paulvl/helpers: dev-master
This package is auto-updated.
Last update: 2024-09-12 04:01:08 UTC
README
[目录]
介绍
快速安装
首先通过Composer安装此包。
您可以运行
composer require paulvl/json-api
或者编辑您项目的composer.json文件以要求paulvl/json-api。
"require-dev": {
"paulvl/json-api": "dev-master"
}
接下来,从终端更新Composer
composer update --dev
一旦包的安装完成,最后一步是添加服务提供者。打开 config/app.php
,并在提供者数组中添加一个新项
PaulVL\JsonApi\JsonApiServiceProvider::class,
最后发布包的配置文件
php artisan vendor:publish
然后将会创建文件 config/json-api.php
。
就这样!您已经准备好了。从终端运行artisan命令以查看新的json-api
命令。
php artisan
模型、控制器和路由
要快速部署您的RESTful JsonApi服务器,您必须使用PaulVL\JsonApi\Model
和PaulVL\JsonApi\Controller
类。
模型
开始使用json-api:make-model
命令创建模型。例如
php artisan json-api:make-model Models\MyModel
这将会创建Models/MyModel.php
文件,其内容如下所示
<?php
namespace App\Models;
use PaulVL\JsonApi\Model;
class MyModel extends Model
{
/**
* The attributes that are mass assignable.
*
* @var array
*/
protected $fillable = [];
/**
* The attributes excluded from queries and the model's JSON form.
*
* @var array
*/
protected $hidden = [];
/**
* The relationship included on the model's JSON form.
*
* @var array
*/
protected $displayable_relations = [
//'relation_example'
];
/**
* Validation rules. If any field needs unique validation, add this rule at the end of the line like example
*
* @var array
*/
static protected $rules = [
//'field_example' => 'required|email|max:255|unique:table,column'
];
/*
public function relation_example() {
return $this->belongsTo('Class', 'foreign_key', 'primary_key');
}
*/
}
如我们所见,有两个新的属性,displayable_relations和rules。
displayable_relations
displayable_relations
属性将加载所有命名关系到json-api结果中,例如
如果我们定义如上所示的relation_example
函数
...
public function relation_example() {
return $this->belongsTo('Class', 'foreign_key', 'primary_key');
}
...
然后将其关系名称添加到displayable_relations
数组中
...
protected $displayable_relations = [
'relation_example'
];
...
这将生成一个类似如下的json-api结果响应
{
"data": [
{
"type": "mymodel",
"id": 1,
"attributes": [
"name": "name",
"class_id": 1,
"created_at": "2015-01-01 00:00:00",
"updated_at": "2015-01-01 00:00:00"
],
"relationships": {
"relation_example": {
"data": {
"type": "class",
"id": 1
}
}
}
}
],
"meta": {
"copyright": "Copyright 2015 Your Business App.",
"authors": [
"Paul Vidal"
]
},
"jsonapi": {
"version": "1.0"
}
}
rules
现在您可以在模型本身中指定验证规则,只需将验证规则添加到rules
数组中即可
...
static protected $rules = [
'field_example' => 'required|email|max:255|unique:table,column'
];
...
注意:如果一个字段需要一个唯一的验证规则,必须在最后指定,这是因为更新规则将自动生成并添加相应的异常规则。要获取更新规则,请使用
getUpdateRules
函数
$update_rules = $mymodel_instance->getUpdateRules();
控制器
继续使用json-api:make-controller命令创建控制器。例如
php artisan json-api:make-controller MyController
这将创建Http/Controllers/MyController.php文件,其内容如下所示
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use PaulVL\JsonApi\Controller as JsonApiController;
use PaulVL\JsonApi\Response;
class MyController extends JsonApiController
{
/**
* Sets the model class that will be handled by this class.
* @var string
*/
protected $model_class = '';
/**
* saveData functions allows you to manual handle save actions triggered from store function on.
* Uncomment this method only if you want to manual handle save actions.
*
* @param array $inputs There are the request's inputs inyected from store function.
* @return PaulVL\JsonApi\response returns response according to action.
*/
/*
public function saveData(array $inputs) {
try {
$response = new Response;
// handle inputs and create and $object and store it.
$response->handleData($object); // You should pass an object to response's handleData method.
return $response->responseCreated(); // You must return a responseCreated.
} catch (Exception $e) { // If any error is fired always return a responseInternalServerError.
$response = new Response;
return $response->responseInternalServerError();
}
}
*/
/**
* updateData functions allows you to manual handle update actions triggered from update function on .
* Uncomment this method only if you want to manual handle update actions.
*
* @param [type] $object Object inyected from update function.
* @param array $inputs There are the request's inputs inyected from store function.
* @return PaulVL\JsonApi\response returns response according to action.
*/
/*
public function updateData($object, array $inputs) {
try {
$response = new Response;
// handle inputs and update the $object.
$response->handleData($user); // You should pass the updated object to response's handleData method.
return $response->response(); // You must return a responseOk or just response.
} catch (Exception $e) { // If any error is fired always return a responseInternalServerError.
$response = new Response;
return $response->responseInternalServerError();
}
}
*/
/**
* arrangeInputs functions allows you to manual handle inputs before validation.
* Uncomment this method only if you want to manual arrange inputs.
*
* @param array $inputs There are the request's inputs inyected from store function.
* @return array $inputs.
*/
/*
public function arrangeInputs(array $inputs) {
// arrange inputs.
return $inputs;
}
*/
/**
* Only if you need to implement create and edit function
* you can override them. They return error 404 as default.
*/
// public function create() { }
// public function edit($id) { }
}
如您所见,控制器中有许多可配置的内容,但最重要的是model_class
属性,在那里您必须设置将由此控制器处理的模型类名,例如
...
protected $model_class = 'App\Models\MyModel';
...
这意味着我们的MyController将处理MyModel。
路由
最后,一旦我们已经创建了MyController控制器和MyModel模型类,我们只需要将资源路由添加到Http/routes.php
文件中,以便访问我们的控制器,如下所示
Route::resource('my-model', 'MyController', ['except' => ['create', 'edit']]);
分页
JsonApi提供了一个简单的方法来实现结果分页。只需将“paginate”和“page”(可选)参数添加到URL中即可,例如
http://example.com/api/user?paginate={items_per_page}&page={current_page}
注意
- 如果没有page参数,分页将设置为第一页。
- 如果page参数设置了一个不存在的值,JsonApi将返回一个包含空data的Ok响应。
查询构建器
JsonApi提供了一个快速运行数据库查询的方法。它可以通过URL请求执行应用程序中的大多数数据库操作,并且适用于所有由Laravel支持的数据库系统。
要运行查询,只需将一个q
参数添加到URL中,并且此参数的内容必须具有以下形式"{clause}={argument_1},...,{argument_n}"
http://example.com/api/user?q={clause}={argument_1},...,{argument_n}
注意:要链式连接句子,只需在句子之间添加一个竖线 |。例如
http://example.com/api/user?q=clause1=arg1,arg2,arg3|clause2=arg1,arg2,arg3
查询句子
其中
最基础的 where 调用需要三个参数。第一个参数是列名。第二个参数是一个操作符,可以是数据库支持的任何操作符。第三个参数是要与列比较的值。
例如,以下是一个验证“votes”列的值是否等于100的查询
http://example.com/api/user?q=where=votes,=,100
为了方便,如果您只想验证一个列是否等于某个给定值,可以直接将值作为where句子的第二个参数传递
http://example.com/api/user?q=where=votes,100
您也可以通过添加两个值作为URL参数来验证一个列是否等于给定值
http://example.com/api/user?votes=100
注意:这仅适用于
where
句子,您也可以链式连接它们http://example.com/api/user?votes=100&name=Pepe
orWhere
您可以链式连接where约束,以及向查询中添加or句子。orWhere
方法接受与where句子相同的参数
http://example.com/api/user?q=where=votes,>,100|orWhere=name,Pepe
whereBetween
whereBetween
句子验证一个列的值是否在两个值之间
http://example.com/api/user?q=whereBetween=votes,10,100
whereNotBetween
whereNotBetween
句子验证一个列的值是否不在两个值之间
http://example.com/api/user?q=whereNotBetween=votes,10,100
whereIn
/ whereNotIn
whereIn
句子验证给定列的值是否包含在给定的数组中
http://example.com/api/user?q=whereIn=votes,10,100
whereNotIn
句子验证给定列的值是否不包含在给定的数组中
http://example.com/api/user?q=whereNotIn=votes,10,100
whereNull
/ whereNotNull
whereNull
句子验证给定列的值是否为NULL
http://example.com/api/user?q=whereNull=updated_at
whereNotNull
句子验证列的值不是NULL
http://example.com/api/user?q=whereNotNull=updated_at
orderBy
orderBy
句子允许您根据给定的列对查询结果进行排序。orderBy
句子的第一个参数是要排序的列,第二个参数控制排序方向,可以是asc
或 desc
http://example.com/api/user?q=orderBy=created_at,desc