timostamm / json-client
使用 Guzzle 和 Symfony Serializer 的简单 JSON API 客户端。
v2.1.0
2023-04-17 10:02 UTC
Requires
- php: ^7.2 || ^8.0
- guzzlehttp/guzzle: ^6.3
- symfony/options-resolver: ^4.0
- symfony/serializer: ^4.0
Requires (Dev)
- phpunit/phpunit: ^8.5.23 || ^9
- psr/log: ^1.0
README
使用 Guzzle 和 Symfony Serializer 的简单 JSON API 客户端。
要实现 API 客户端,您可以扩展 AbstractApiClient 并编写您的方法,使用 Guzzle HTTP 客户端进行传输。
class MyClient extends AbstractApiClient { /** * @throws TransferException */ public function send(Model $model):void { // The data will automatically be // serialized to JSON. $this->http->post('model', [ 'data' => $model ]); } /** * @param int $id * @throws TransferException * @returns Model */ public function get(int $id):Model { return $this->http->get('model/'.$id, [ 'deserialize_to' => Model::class ]); } }
所有功能都实现为中间件,AbstractApiClient 只是为您配置了 Guzzle HandlerStack。
提供的中间件
序列化
参见 DeserializeResponseMiddleware
和 SerializeRequestBodyMiddleware
。
服务器错误消息
ServerMessageMiddleware
提供了对 JSON 错误消息的支持。
响应期望
如果您想确保响应具有特定的头部、内容类型或其他功能,请使用 ResponseExpectationMiddleware
。
日志记录
还有一个中间件可以记录所有 HTTP 请求(以及相应的响应或异常),请参阅 HttpLoggingMiddleware
。
有可用的 Psr\Log\LoggerInterface
适配器。
此中间件默认不添加,因为顺序很重要:HttpLoggingMiddleware 必须是最后一个添加的。