Skip to content

Commit

Permalink
Merge pull request #20 from thormeier/utils-batch-client
Browse files Browse the repository at this point in the history
Add documentation for BatchClient, BatchResult and BatchException
  • Loading branch information
sagikazarmark committed Oct 31, 2015
2 parents 318e3cf + 35bff47 commit f1b2b86
Showing 1 changed file with 52 additions and 0 deletions.
52 changes: 52 additions & 0 deletions docs/utils.md
Original file line number Diff line number Diff line change
Expand Up @@ -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());
}
```

0 comments on commit f1b2b86

Please sign in to comment.