扩展Guzzle 6的默认响应

时间:2015-10-21 09:50:47

标签: php http guzzle guzzle6

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

 Unified Dependency "nunit.framework, Version=2.6.4.14350, Culture=neutral, PublicKeyToken=96d09a1eb7f44a77".
         Using this version instead of original version "2.6.3.13283" in "D:\Agents\Agent1\c81e9061\eServices\.NugetLocalCache\EnterpriseApplications.Framework.Testing.1.0.0.0\lib\net45\EnterpriseApplications.Framework.Testing.dll" because AutoUnify is 'true'.
         Using this version instead of original version "2.6.3.13283" in "D:\Agents\Agent1\c81e9061\eServices\.NugetLocalCache\EnterpriseApplications.Framework.Testing.Mvc.1.0.0.0\lib\net451\EnterpriseApplications.Framework.Testing.Mvc.dll" because AutoUnify is 'true'.
         Could not resolve this reference. Could not locate the assembly "nunit.framework, Version=2.6.4.14350, Culture=neutral, PublicKeyToken=96d09a1eb7f44a77". Check to make sure the assembly exists on disk. If this reference is required by your code, you may get compilation errors.

目前的目标是在响应中添加$client = new GuzzleHttp\Client(['base_uri' => 'https://foo.com/api/']); $response = $client->request('GET', 'test'); // I want my own class instance here 函数(但它可能是其他内容)。我在guzzle 6文档中丢失了。

1 个答案:

答案 0 :(得分:2)

我强烈建议不要通过继承扩展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的信息herehere

除非将中间件附加到堆栈处理程序,否则不要将其附加到客户端。

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

可以找到有关Guzzle Middleware的更多信息here