如何扩展默认的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文档中丢失了。
答案 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的信息here和here
除非将中间件附加到堆栈处理程序,否则不要将其附加到客户端。
$stack->push(GuzzleHttp\Middleware::mapResponse(function Psr\Http\Message\ResponseInterface $response) {
return new JsonResponse($response);
});
可以找到有关Guzzle Middleware的更多信息here。