-
Notifications
You must be signed in to change notification settings - Fork 74
Response
Zewail edited this page Sep 11, 2018
·
2 revisions
响应生成器提供了一个流畅的接口去方便的建立一个定制化的响应
要利用响应生成器, 你的控制器需要使用Zewail\Api\Api
trait, 可以建立一个通用控制器,然后你的所有的 API 控制器都继承它。
namespace app\index\controller;
use think\Controller;
use Zewail\Api\Api;
class BaseController extends Controller
{
use Api;
}
然后你的控制器可以直接继承基础控制器。响应生成器可以在控制器里通过 $response
属性获取。
当然,也可以使用门面(Facade)来获取
namespace app\index\controller;
use Zewail\Api\Facades\Response as ApiResponse;
class IndexController
{
public function index() {
return ApiResponse::array([]);
}
}
// 简单的成功响应, 默认200状态码, 可以在第二个参数改变
// 使用 trait, 其他方法都可以使用该方法,下面都使用 Facade 演示
return $this->response->array($user->toArray());
// 使用 Facade
return ApiResponse::success('Success', 200);
$user = User::get($id);
return ApiResponse::array($user->toArray());
$user = User::get($id);
return ApiResponse::item($user);
$users = User::all();
return ApiResponse::collection($users);
$users = User::paginate(10);
return ApiResponse::paginator($users);
返回一个错误响应
return ApiResponse::BadRequest();
当然也可以返回成功的响应
return ApiResponse::OK($data);
方法名 | 状态码 | 说明 |
---|---|---|
Continue | 100 | Continue |
SwitchingProtocols | 101 | Switching Protocols |
Processing | 102 | Processing |
EarlyHints | 103 | Early Hints |
OK | 200 | OK |
Created | 201 | Created |
Accepted | 202 | Accepted |
NonAuthoritativeInformation | 203 | Non-Authoritative Information |
NoContent | 204 | No Content |
ResetContent | 205 | Reset Content |
PartialContent | 206 | Partial Content |
MultiStatus | 207 | Multi-Status |
AlreadyReported | 208 | Already Reported |
IMUsed | 226 | IM Used |
MultipleChoices | 300 | Multiple Choices |
MovedPermanently | 301 | Moved Permanently |
Found | 302 | Found |
SeeOther | 303 | See Other |
NotModified | 304 | Not Modified |
UseProxy | 305 | Use Proxy |
TemporaryRedirect | 307 | Temporary Redirect |
PermanentRedirect | 308 | Permanent Redirect |
BadRequest | 400 | Bad Request |
Unauthorized | 401 | Unauthorized |
PaymentRequired | 402 | Payment Required |
Forbidden | 403 | Forbidden |
NotFound | 404 | Not Found |
MethodNotAllowed | 405 | Method Not Allowed |
NotAcceptable | 406 | Not Acceptable |
ProxyAuthenticationRequired | 407 | Proxy Authentication Required |
RequestTimeou | 408 | Request Timeou |
Conflict | 409 | Conflict |
Gone | 410 | Gone |
LengthRequired | 411 | Length Required |
PreconditionFailed | 412 | Precondition Failed |
PayloadTooLarge | 413 | Payload Too Large |
URITooLong | 414 | URI Too Long |
UnsupportedMediaType | 415 | Unsupported Media Type |
RangeNotSatisfiable | 416 | Range Not Satisfiable |
ExpectationFailed | 417 | Expectation Failed |
IAmATeapot | 418 | I'm a teapot |
MisdirectedRequest | 421 | Misdirected Request |
UnprocessableEntity | 422 | Unprocessable Entity |
Locked | 423 | Locked |
FailedDependency | 424 | Failed Dependency |
UnorderedCollection | 425 | Unordered Collection |
UpgradeRequired | 426 | Upgrade Required |
PreconditionRequired | 428 | Precondition Required |
TooManyRequests | 429 | Too Many Requests |
RequestHeaderFieldsTooLarge | 431 | Request Header Fields Too Large |
UnavailableForLegalReasons | 451 | Unavailable For Legal Reasons |
InternalServerError | 500 | Internal Server Error |
NotImplemented | 501 | Not Implemented |
BadGateway | 502 | Bad Gateway |
ServiceUnavailable | 503 | Service Unavailable |
GatewayTimeout | 504 | Gateway Timeout |
HTTPVersionNotSupported | 505 | HTTP Version Not Supported |
VariantAlsoNegotiates | 506 | Variant Also Negotiates |
InsufficientStorage | 507 | Insufficient Storage |
LoopDetected | 508 | Loop Detected |
NotExtended | 510 | Not Extended |
NetworkAuthenticationRequired | 511 | Network Authentication Required |
return ApiResponse::item($user)->addMeta('foo', 'bar');
或者直接设置 Meta 数据的数组
return ApiResponse::item($user)->setMeta($meta);
return ApiResponse::item($user)->setCode(200);
// 提供两种设置方式
return ApiResponse::item($user)->addHeader('X-Foo', 'Bar');
return ApiResponse::item($user)->addHeader(['X-Foo' => 'Bar']);
return ApiResponse::item($user)->setLastModified($time);
return ApiResponse::item($user)->setETag($eTag);
return ApiResponse::item($user)->setExpires($time);
return ApiResponse::item($user)->setCacheControl($cache);
其中item
collection
paginator
具有两个参数,第一个参数为模型数据,第二个参数为数据过滤列表
// 如查询出来的$user具有id, name, age, mobile等属性
// 在设置了第二个参数为['id', 'name', 'age']后,将会过滤其他属性,只返回给接口列出的属性
return ApiResponse::item($user, ['id', 'name', 'age']);
return ApiResponse::collection($users, ['id', 'name', 'age']);
return ApiResponse::paginator($users, ['id', 'name', 'age']);
或者通过only
与except
方法过滤数据
// 只选择模型中的id、name、age属性
return ApiResponse::only(['id', 'name', 'age'])->item($user);
// 排除模型属性age
return ApiResponse::except(['age'])->item($user);
// 还可以一起使用, 选择id、name、age属性后排除age
return ApiResponse::only(['id', 'name', 'age'])->except(['age'])->item($user);
提供了一个配置文件用于数据过滤或者说是数据资源的集中管理
使用该功能需要在thinkphp中新建一个配置文件resources.php
return [
// 用户相关接口
// 例如设置一些用户的相关接口资源
'user.age' => ['id', 'name', 'age'],
'user.mobile' => ['id', 'name', 'mobile'],
];
然后在返回接口数据的时候在item
collection
paginator
第二个参数传入该标识即可
// 返回{'data': {'id':1, 'name': 'xiaoming', 'age': 20}}
return ApiResponse::item($user, 'user.age');
// 返回{'data': {'id':1, 'name': 'xiaoming', 'mobile': '13777777777'}}
return ApiResponse::item($user, 'user.mobile');
或者通过only
与except
方法
// 返回{'data': {'id':1, 'name': 'xiaoming', 'age': 20}}
return ApiResponse::only('user.age')->item($user);
// 返回{'data': {'id':1, 'name': 'xiaoming', 'mobile': '13777777777'}}
return ApiResponse::only('user.mobile')->item($user);
item、collection、paginator的第二个过滤参数属性,会覆盖only与except方法
如果默认配置Array
,想返回DataArray
格式的数据,可以:
// 返回Array格式的数据
return ApiResponse::item($user)->serializer('Array');
// 返回DataArray格式的数据
return ApiResponse::item($user)->serializer('DataArray');