xp-forge/rest-api
Composer 安装命令:
composer require xp-forge/rest-api
包简介
Rest API
README 文档
README
Annotation-based REST APIs
Example
use web\rest\{Get, Post, Resource, Response}; #[Resource('/users')] class Users { #[Get('/')] public function listUsers($max= 10) { // $max comes from request parameter "max", defaulting to 10 // ... } #[Get('/{id}')] public function findUser($id) { // $id is extracted from URL segment // ... } #[Post('/')] public function createUser($user) { // $user is deserialized from the request body according to its content type // ... return Response::created('/users/{id}', $id)->entity($created); } }
Wire it together in a web application:
use web\Application; class Service extends Application { /** @return [:var] */ public function routes() { return ['/users' => new RestApi(new Users())]; } }
Run it using:
$ xp -supervise web Service @xp.web.Serve(HTTP @ peer.ServerSocket(resource(type= Socket, id= 88) -> tcp://127.0.0.1:8080)) # ...
Then call curl -i localhost:8080/users/1549.
Parameter sources
Method parameters are automatically extracted from URI segments if their name matches the path segment in the curly braces. For requests without bodies (GET, HEAD, DELETE, OPTIONS), the value is extracted from request parameters. For requests with bodies (POST, PUT and PATCH), the body is deserialized and passed.
To supply the source explicitely, you can use parameter attributes:
#[Param]will fetch the parameter from the request parameter named "max".#[Param('maximum')]will fetch the parameter from the request parameter named "maximum".#[Value]will use a request value (which was previously passed e.g. inside a filter viapass()) for the parameter#[Header('Content-Type')]will use the Content-Type header as value for the parameter#[Entity]will deserialize the request body and pass its value to the parameter#[Body]will pass the request body as a string#[Stream]will pass anio.streams.InputStreaminstance to stream the request body to the parameter#[Request]will pass the completeweb.Requestobject
Parameter conversions
Parameters can be converted from their input. This library comes with a built-in conversion named SeparatedBy:
use web\rest\{Resource, Get, Param, SeparatedBy}; #[Resource('/api/trainings')] class Trainings { #[Get('/completed')] public function completed(#[Param, SeparatedBy(',')] array $orgunits) { return $this->repository->find(['status' => 'COMPLETED', 'orgunits' => $orgunits]); } }
The orgunits parameter can now be supplied in the URL as follows: https://example.com/api/trainings/completed?orgunits=A,B and the resulting value inside $orgunits will be ["A", "B"]. User-defined conversions can be supplied by implementing the web.rest.Conversion interface.
Matrix parameters
This library supports parameters inside path segments, e.g. https://example.com/api/trainings/status=COMPLETED;orgunits=A,B/authors:
use web\rest\{Resource, Get, Matrix}; #[Resource('/api/trainings')] class Trainings { #[Get('/{filter}/authors')] public function authors(#[Matrix] array $filter) { $authors= []; foreach ($this->repository->find($filter) as $training) { $authors[$training->author->id()]= $training->author; } return $authors; } }
The resulting value inside $filter will be ["status" => "COMPLETED", "orgunits" => ["A", "B"]].
Return types
Methods can return anything, which is then serialized and written to the response with a "200 OK" status. If you want greater control over the response, you can use the web.rest.Response class. It provides a fluent DSL for handling various scenarios.
Example:
return Response::created('/users/{id}', $id)->type('application/vnd.example.type-v2+json')->entity($user);
Creation:
Response::ok()- 200 OKResponse::created([string $location])- 201 Created, optionally with a Location headerResponse::accepted()- 202 AcceptedResponse::noContent()- 204 No contentResponse::see(string $location)- 302 Found and a Location headerResponse::notModified()- 304 Not modifiedResponse::notFound([string $message])- 404 Not found and an optional message, which is serializedResponse::notAcceptable([string $message])- 406 Not acceptable and an optional message, which is serializedResponse::error(int $code[, string $message])- An error and an optional message, which is serializedResponse::status(int $code)- Any other status code
Headers:
$response->type(string $mime)will set the Content-Type header$response->header(string $name, string $value)will set a header with a given name and value
Body:
$response->entity(var $value)will sent a value, serializing it$response->stream(io.streams.InputStream $in[, int $size])will stream a response$response->body(string $bytes)will write the given raw bytes to the response
Asynchronous invocation
The following code will run the upload function asynchronously, continuing to serve requests while file contents are being transmitted.
use io\Folder; use web\rest\{Async, Post, Resource, Response}; #[Resource('/api')] class Uploads { public function __construct(private Folder $folder) { } #[Post('/files')] public function upload(#[Request] $req) { return new Async(function() use($req) { if ($multipart= $req->multipart()) { foreach ($multipart->files() as $file) { yield from $file->transmit($this->folder); } } return Response::ok(); }); } }
See also
https://github.com/thekid/shorturl - URL Shortener service
xp-forge/rest-api 适用场景与选型建议
xp-forge/rest-api 是一款 基于 PHP 开发的 Composer 扩展包,目前已累计 42.57k 次下载、GitHub Stars 达 2, 最近一次更新时间为 2018 年 02 月 01 日, 在 PHP 生态内属于活跃度较高的组件。
它主要适用于以下技术方向: 「module」 「xp」 等业务场景。在实际项目中,围绕这些方向常见需要落地的问题包括:接口对接、性能调优、并发安全、与既有框架(Laravel / ThinkPHP / Yii / Webman 等)的兼容适配,以及生产环境的日志埋点与稳定性保障。
我们在过去多个企业项目中使用过 xp-forge/rest-api 或与其功能相近的方案,如果你在选型或落地过程中遇到问题,例如 版本兼容、二次改造、私有化封装、与内部系统对接、生产 BUG 排查,欢迎联系我们协助评估。
基于 xp-forge/rest-api 在你已有业务上做功能扩展、字段裁剪、UI 适配、与内部账号 / 权限 / 日志系统的深度对接。
线上偶发问题、内存泄漏、慢查询、并发异常等排查修复;针对高流量场景做缓存、队列、索引层面的调优。
承接完整的项目从需求 → 设计 → 开发 → 上线 → 长期运维;也可按月提供技术保姆服务。
与 xp-forge/rest-api 相关的其它包
同方向 / 同关键字的高下载量 PHP Composer 包推荐,方便对比选型:
bootstrap select field module implementing http://silviomoreto.github.io/bootstrap-select/
Yii2 module to manage website content. Kind of a CMS...
Codeurx Modular is simply a package for Laravel to help you create and manage modules.
User Module for the Attogram Framework
Info Module for the Attogram Framework
Contact Form Module for the Attogram Framework
统计信息
- 总下载量: 42.57k
- 月度下载量: 0
- 日度下载量: 0
- 收藏数: 2
- 点击次数: 10
- 依赖项目数: 0
- 推荐数: 0
其他信息
- 授权协议: BSD-3-Clause
- 更新时间: 2018-02-01

