15. Mock Handler
$handler = new MockHandler([
new Response(200, ['X-Foo' => 'Bar']),
new Response(202, ['Content-Length' => 0]),
new RequestException("Error", new Request('GET',
'test'))
]);
16. use GuzzleHttpClient;
use GuzzleHttpHandlerMockHandler;
use GuzzleHttpPsr7Response;
use GuzzleHttpPsr7Request;
use GuzzleHttpExceptionRequestException;
$handler = new MockHandler([
new Response(200, ['X-Foo' => 'Bar']),
new Response(202, ['Content-Length' => 0]),
new RequestException("Error", new Request('GET', 'test'))
]);
$client = new Client(['handler' => $handler]);
$response = $client->request('GET', '/');
echo $response->getStatusCode() . PHP_EOL; // => 200
$response = $client->request('GET', '/');
echo $response->getStatusCode() . PHP_EOL; // => 202
$response = $client->request('GET', '/'); // => RequestException
Mock Handler
18. Handler
you can pass a callable
$client = new Client([
'handler' => $callable
]);
19. Handler
spec of handler
handler:
(callable) Function that transfers HTTP requests over the wire.
The function is called with a
Psr7HttpMessageRequestInterface and array of transfer
options,
and must return a
GuzzleHttpPromisePromiseInterface
20. Handler
spec of handler
function (RequestInterface $request, array $options)
{
return $promise_interface;
}
or
public function __invoke(
RequestInterface $request, array $options
)
{
return $promise_interface;
}
22. Handler
should be callable
$client = new Client([
'handler' => 1
]);
PHP Fatal error: Uncaught InvalidArgumentException: handler
must be a callable