From 35bff479ed3e6d0e42f72b74b0da9184edc790ce Mon Sep 17 00:00:00 2001 From: Pascal Thormeier Date: Sat, 31 Oct 2015 16:27:05 +0100 Subject: [PATCH] Add documentation for BatchClient, BatchResult and BatchException --- docs/utils.md | 52 +++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 52 insertions(+) diff --git a/docs/utils.md b/docs/utils.md index 913ff43..4adaa6d 100644 --- a/docs/utils.md +++ b/docs/utils.md @@ -23,3 +23,55 @@ $foo = $client->get('http://example.com/foo'); $bar = $client->get('http://example.com/bar', ['accept-encoding' => 'application/json']); $post = $client->post('http://example.com/update', [], 'My post body'); ``` + +## BatchClient + +This client wraps a HttpClient and extends it with the possibility to send an array of requests and to retrieve their responses as a `BatchResult`. + +``` php +use Http\Discovery\HttpClientDiscovery; +use Http\Discovery\MessageFactoryDiscovery; + +$messageFactory = MessageFactoryDiscovery::find(); + +$requests = [ + $messageFactory->createRequest('GET', 'http://example.com/foo'), + $messageFactory->createRequest('POST', 'http://example.com/update', [], 'My post body'), +]; + +$client = new BatchClient( + HttpClientDiscovery::find() +); + +$batchResult = $client->sendRequests($requests); +``` + +The `BatchResult` itself is an object that contains responses for all requests sent. It provides methods that give appropriate information based on a given request. + +``` php +$requests = [ + $messageFactory->createRequest('GET', 'http://example.com/foo'), + $messageFactory->createRequest('POST', 'http://example.com/update', [], 'My post body'), +]; + +$batchResult = $client->sendRequests($requests); + +if ($batchResult->hasResponses()) { + $fooSuccessful = $batchResult->isSuccesful($requests[0]); + $updateResponse = $batchResult->getResponseFor($request[1]); +} +``` + +If one or more of the requests throw exceptions, they are added to the `BatchResult` and the `BatchClient` will ultimately throw a `BatchException` containing the `BatchResult` and therefore its exceptions. + +``` php +$requests = [ + $messageFactory->createRequest('GET', 'http://example.com/update'), +]; + +try { + $batchResult = $client->sendRequests($requests); +} catch (BatchException $e) { + var_dump($e->getResult()->getExceptions()); +} +```