【问题标题】:Extends Guzzle 6 default response扩展 Guzzle 6 默认响应
【发布时间】:2016-01-20 06:12:55
【问题描述】:

如何扩展默认的 guzzle 响应对象?

$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 文档中。

【问题讨论】:

标签: php http guzzle guzzle6


【解决方案1】:

我强烈建议不要通过继承扩展 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.
}

可以在herehere 找到有关ResponseInterface 的信息

您不会将它附加到客户端,而是将中间件附加到堆栈处理程序。

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

更多关于 Guzzle 中间件的信息可以在here找到。

【讨论】:

  • 好的,谢谢。 “我强烈建议不要扩展GuzzleHttp\Http\Message\Response”-> 为什么?这似乎更容易。如果GuzzleHttp\Http\Message\Response 实现Psr\Http\Message\ResponseInterface,则没有破坏某些东西的风险(感谢界面),我只想将它与 guzzle 一起使用(因此无需最大化其可用性)。无论如何,即使我实现了接口,我如何将它附加到客户端?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-05-12
  • 2016-12-09
  • 2012-04-26
  • 2017-06-28
相关资源
最近更新 更多