phapi / endpoint
包含所有Phapi端点应扩展的端点类。具有处理OPTIONS请求的内置功能。
Requires
- php: >=5.6.0
- phapi/contract: 1.*
- phapi/exception: 1.*
- psr/http-message: 1.*
Requires (Dev)
- codeclimate/php-test-reporter: dev-master
- mockery/mockery: 0.9.*
- phpunit/phpunit: 4.*
This package is not auto-updated.
Last update: 2021-02-05 22:36:48 UTC
README
所有成功的请求(除非使用缓存)都将路由到应处理请求的端点,并返回请求内容。
安装
此包默认由Phapi框架安装。要使用包,可以使用composer单独安装。
$ composer require phapi/endpoint:1.*
基本用法
端点包含处理请求的方法。如果端点应支持GET请求,则必须存在get()
方法。每个方法必须返回客户端发送的响应体的内容。内容必须格式化为数组。然后序列化器将数组序列化为正确的格式。
<?php namespace Phapi\Endpoint; class Blog extends Endpoint { public function get($postid) // $postid is an url param, ex: /blog/{postid:i}/ { return [ 'Title' => 'A Phapi tutorial, part 1', 'Publish date' => '2015-01-01', 'Author' => 'John Doe', ... ]; } }
所有扩展Endpoint类的端点都有请求、响应和依赖注入容器可用:$this->request
、$this->response
、$this->container
。
状态码
默认状态码是200。可以通过访问响应对象并设置新的状态码来更改状态码。
<?php public function get() { // Change status code on the response to a 201 CREATED: $this->response = $this->response->withStatusCode(201); }
错误和异常
处理错误应该简单,这就是为什么Phapi有许多预定义异常。使用这些异常,只需抛出它们即可向客户端发送一个漂亮的响应。
<?php namespace Phapi\Endpoint; use Phapi\Exception\NotFound; class Blog extends Endpoint { public function get() { throw new NotFound( 'The article you are looking for does not exist.', 23, null, 'https://example.local/docs/23/' ); } }
这将导致如下响应(以JSON为例)
{ "errors": { "message": "The article you are looking for does not exist.", "code": 23, "description": "The URI requested is invalid or the resource requested, such as a user, does not exists. Also returned when the requested format is not supported by the requested method.", "link": "https://example.local/docs/23/" } }
重定向
应该通过更新响应对象来处理重定向。
<?php public function get() { // This endpoint has moved permanently $this->response = $this->response->withStatusCode(301); $this->response = $this->response->withAddedHeader('Location': 'http://example.local/endpoint/new'); }
HEAD请求
所有HEAD请求都由端点自动处理,通过检查是否实现了get()
方法。如果实现了,它将调用get()
方法,以便创建所有头部,但会忽略主体,因为HEAD请求不应返回主体。
OPTIONS请求
端点自动包含处理OPTIONS请求的功能,通过查看实现的方法和PHPDoc来设置头部和生成主体。该方法返回支持的内容类型、允许的方法以及API文档(如果存在)。
使用PHPDoc和以@api开头的标签来记录API。
<?php /** * @apiUri /blog/12 * @apiDescription Retrieve the blogs information like * id, name and description * @apiParams id int * @apiResponse id int Blog ID * @apiResponse name string The name of the blog * @apiResponse description string A description of the blog * @apiResponse links string * A list of links */ public function get() ...
可以使用这种方式进行相当高级的文档记录。
在OPTIONS请求中返回响应体可能略显不寻常,但这使得API具有自描述性。这使得通过实际使用API本身即可浏览、使用和查看API的文档。
Phapi
端点(Endpoint)是Phapi框架中使用的Phapi包。
许可
端点遵循MIT许可协议 - 有关详细信息,请参阅license.md文件。
贡献
欢迎贡献、修复bug等。贡献方式。