此软件包已被废弃,不再维护。未建议替代软件包。

XP 框架的 REST 客户端和服务器 API

v10.0.0 2018-08-24 22:18 UTC

README

Build Status on TravisCI XP Framework Module BSD Licence Required PHP 5.6+ Supports PHP 7.0+ Required HHVM 3.4+ Latest Stable Version

客户端

入口点

Endpoint 类是该 API 的入口点。使用 REST 服务的端点 URL 创建一个新实例,然后调用其 resource() 方法来操作资源。

创建:POST

$api= new Endpoint('http://api.example.com/');
$response= $api->resource('users')->post(['name' => 'Test'], 'application/json');

// Check status codes
if (201 !== $response->status()) {
  throw new IllegalStateException('Could not create user!');
}

// Retrieve response headers
$url= $response->header('Location');

读取:GET / HEAD

$api= new Endpoint('http://api.example.com/');

// Unmarshal to object by optionally passing a type; otherwise returned as map
$user= $api->resource('users/self')->get()->data(User::class);

// Test for existance with HEAD
$exists= (200 === $api->resource('users/1549')->head()->status());

// Pass parameters
$list= $api->resource('user')->get(['page' => 1, 'per_page' => 50])->data();

更新:PUT / PATCH

$api= new Endpoint('http://api.example.com/');
$resource= $api->resource('users/self')
  ->using('application/json')
  ->accepting('application/json')
;

// Default content type and accept types set on resource used
$updated= $resource->put(['name' => 'Tested', 'login' => $mail])->data();

// Resources can be reused!
$updated= $resource->patch(['name' => 'Changed'])->data();

删除:DELETE

$api= new Endpoint('http://api.example.com/');

// Pass segments
$api->resource('user/{id}', ['id' => 6100])->delete();

执行

如果需要完全控制请求,请使用通用的 execute() 方法。

use webservices\rest\Endpoint;
use webservices\rest\RestRequest;
use peer\http\HttpConstants;

$api= new Endpoint('http://api.example.com/');

$request= (new RestRequest('/resource/{id}'))
 ->withMethod(HttpConstants::GET)
 ->withSegment('id', 5000)
 ->withParameter('details', 'true')
 ->withHeader('X-Binford', '6100 (more power)'
;

$response= $api->execute($request);
$content= $response->content();            // Raw data as string
$value= $response->data();                 // Deserialize to map

反序列化

REST API 支持通过传递类型到 data() 方法来自动结果反序列化。

use com\example\api\types\Person;

$person= $response->data(Person::class);
$strings= $response->data('string[]');
$codes= $response->data('[:int]');

身份验证

基本身份验证通过在端点 URL 中嵌入凭据来支持。

use webservices\rest\Endpoint;

$api= new Endpoint('http://user:pass@api.example.com/');