timostamm/json-client

使用 Guzzle 和 Symfony Serializer 的简单 JSON API 客户端。

v2.1.0 2023-04-17 10:02 UTC

This package is auto-updated.

Last update: 2024-09-17 16:50:33 UTC


README

build Packagist PHP Version GitHub tag License

使用 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。

提供的中间件

序列化

参见 DeserializeResponseMiddlewareSerializeRequestBodyMiddleware

服务器错误消息

ServerMessageMiddleware 提供了对 JSON 错误消息的支持。

响应期望

如果您想确保响应具有特定的头部、内容类型或其他功能,请使用 ResponseExpectationMiddleware

日志记录

还有一个中间件可以记录所有 HTTP 请求(以及相应的响应或异常),请参阅 HttpLoggingMiddleware

有可用的 Psr\Log\LoggerInterface 适配器。

此中间件默认不添加,因为顺序很重要:HttpLoggingMiddleware 必须是最后一个添加的。