sc0 / rest-client
简单的PHP Rest客户端
2.2.0
2022-07-04 20:20 UTC
Requires
- php: >=8.1
- ext-libxml: *
- ext-simplexml: *
- guzzlehttp/guzzle: ^7.0
Requires (Dev)
- phpunit/phpunit: ^9.5
README
这是一个简单且可扩展的REST客户端。
基本用法
use Sc\RestClient\Client\Client; use Sc\RestClient\ResponseParser\JsonResponseParser; $client = new Client('https://api.foo.bar', new JsonResponseParser()); $resource = 'zombies'; // retrieve all objects (will produce GET /zombies/) $client->getAll($resource); // create a new resource (will produce POST /zombies/ with following data) $created = $client->create($resource, [ 'name' => 'Shaun', 'age' => 29, ]); // 'create' API should return data or 'Location' header with created resource URI $id = $created['id']; // retrieve single object (will produce GET /zombies/123/) $client->get($resource, $id); // update full resource (will produce PUT /zombies/123/) $updated = $client->update($resource, $id, [ 'name' => 'Shaun', 'age' => 30, ]); // update resource partially (will produce PATCH /zombies/123/) $updated = $client->update($resource, $id, [ 'age' => 31, ]); // delete resource (will produce DELETE /zombies/123/) $client->delete($resource, $id);
更改响应格式
use Sc\RestClient\Client\Client; use Sc\RestClient\ResponseParser\XmlResponseParser; $client = new Client('https://api.foo.bar', new XmlResponseParser('root_tag_name'));
实现自己的响应解析器
只需实现 Sc\RestClient\ResponseParser\ResponseParserInterface#parseResponse 并处理响应
自定义API认证
use Sc\RestClient\Client\Client; use Sc\RestClient\ResponseParser\JsonResponseParser; use Sc\RestClient\AuthenticationProvider\QueryParameterProvider; use Sc\RestClient\AuthenticationProvider\HeaderProvider $client = new Client('https://api.foo.bar', new JsonResponseParser()); $client->useAuthenticator(new QueryParameterProvider('api_key', 'abcd1234')); // each request will be followed with ?api_key=abcd1234 query string // or $client->useAuthenticator(new HeaderProvider('X-Auth-Header', 'abcd1234')); // each request will be followed with header "X-Auth-Header: abcd1234"
实现自己的认证器
Sc\RestClient\AuthenticationProvider\AuthenticationProviderInterface#addAuthentificationInfo 将处理原始请求并根据您的需求修改它,例如X.509证书
请求签名
@待办