扩展 Guzzle 6 个默认响应

Extends Guzzle 6 default response

如何扩展默认 guzzle 响应 object?

$client = new GuzzleHttp\Client(['base_uri' => 'https://foo.com/api/']);
$response = $client->request('GET', 'test'); // I want my own class instance here

当前的目标是添加一个 json 函数作为响应(但也可以是其他东西)。我迷失在 guzzle 6 文档中。

我强烈建议不要通过继承扩展 GuzzleHttp\Http\Message\Response。推荐的方法是使用组合来实现 Psr\Http\Message\ResponseInterface,然后将对 ResponseInterface 方法的所有调用代理到封闭的对象。这将最大限度地提高其可用性。

class JsonResponse implements Psr\Http\Message\ResponseInterface {
    public function __construct(Psr\Http\Message\ResponseInterface $response) {
        $this->response = $response;
    }

    public function getHeaders() {
        return $this->response->getHeaders();
    }

    public function getBodyAsJson() {
        return json_decode($this->response->getBody()->__toString());
    }
    // I will leave the remaining methods of the Psr\Http\Message\ResponseInterface for you to look up.
}

可以找到ResponseInterface的信息here and here

与其将中间件附加到堆栈处理程序,不如将其附加到客户端。

$stack->push(GuzzleHttp\Middleware::mapResponse(function Psr\Http\Message\ResponseInterface $response) {
    return new JsonResponse($response);  
});

可以找到有关 Guzzle 中间件的更多信息 here