rap-2-h
rap-2-h

Reputation: 32048

Extends Guzzle 6 default response

How can I extends the default guzzle response object?

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

The current goal is to add a json function in response (but it could be something else). I'm a lost in guzzle 6 documentation.

Upvotes: 1

Views: 1541

Answers (1)

Shaun Bramley
Shaun Bramley

Reputation: 2047

I would strongly advise against extending GuzzleHttp\Http\Message\Response via inheritance. The recommended method would be to use composition to implement Psr\Http\Message\ResponseInterface and then proxy all calls to the ResponseInterface methods to the enclosed object. This would maximize its usability.

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.
}

Information on the ResponseInterface can be found here and here

You don't attach it to the client so much as you attach middleware to the stack handler.

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

More information on Guzzle Middleware can be found here.

Upvotes: 2

Related Questions