Skip to content

Commit ae9d39c

Browse files
committed
Merge pull request #21 from joelwurtz/feature/async
Add documentation for async client
2 parents 6906a2b + 1ff4919 commit ae9d39c

File tree

3 files changed

+177
-20
lines changed

3 files changed

+177
-20
lines changed

docs/discovery.md

Lines changed: 30 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -19,7 +19,7 @@ composer require "php-http/discovery"
1919

2020
## HTTP Client Discovery
2121

22-
This type of discovery finds installed HTTP Clients.
22+
This type of discovery finds an HTTP Client implementation.
2323

2424
``` php
2525
use Http\Client\HttpClient;
@@ -33,7 +33,7 @@ class MyClass
3333
protected $httpClient;
3434

3535
/**
36-
* @param HttpClient|null $httpClient to do HTTP requests.
36+
* @param HttpClient|null $httpClient Client to do HTTP requests, if not set, autodiscovery will be used to find a HTTP client.
3737
*/
3838
public function __construct(HttpClient $httpClient = null)
3939
{
@@ -42,10 +42,34 @@ class MyClass
4242
}
4343
```
4444

45+
## HTTP Async Client Discovery
46+
47+
This type of discovery finds a HTTP Async Client implementation.
48+
49+
``` php
50+
use Http\Client\HttpAsyncClient;
51+
use Http\Discovery\HttpAsyncClientDiscovery;
52+
53+
class MyClass
54+
{
55+
/**
56+
* @var HttpAsyncClient
57+
*/
58+
protected $httpAsyncClient;
59+
60+
/**
61+
* @param HttpAsyncClient|null $httpAsyncClient Client to do HTTP requests, if not set, autodiscovery will be used to find an asynchronous client.
62+
*/
63+
public function __construct(HttpAsyncClient $httpAsyncClient = null)
64+
{
65+
$this->httpAsyncClient = $httpAsyncClient ?: HttpAsyncClientDiscovery::find();
66+
}
67+
}
68+
```
4569

4670
## PSR-7 Message Factory Discovery
4771

48-
This type of discovery finds installed [PSR-7](http://www.php-fig.org/psr/psr-7/) Message implementations and their [factories](message-factory.md).
72+
This type of discovery finds a [message factory](message-factory.md) for a [PSR-7](http://www.php-fig.org/psr/psr-7/) Message implementation.
4973

5074
``` php
5175
use Http\Message\MessageFactory;
@@ -71,7 +95,7 @@ class MyClass
7195

7296
## PSR-7 URI Factory Discovery
7397

74-
This type of discovery finds installed [PSR-7](http://www.php-fig.org/psr/psr-7/) URI implementations and their factories.
98+
This type of discovery finds a uri factory for a [PSR-7](http://www.php-fig.org/psr/psr-7/) URI implementation.
7599

76100
``` php
77101
use Http\Message\UriFactory;
@@ -117,7 +141,8 @@ Classes registered manually are put on top of the list.
117141

118142
### Writing your own discovery
119143

120-
Each discovery service is based on the `ClassDiscovery` and has to specify a `cache` field and a `class` field to specify classes for the corresponding service. The fields need to be redeclared in each discovery class. If `ClassDiscovery` would declare them, they would be shared between the discovery classes which would make no sense.
144+
Each discovery service is based on the `ClassDiscovery` and has to specify a `cache` property and a `class` property to specify classes for the corresponding service.
145+
Since they are static, this properties need to be redeclared in each discovery class. If `ClassDiscovery` would declare them, they would be shared between the discovery classes which would make no sense.
121146

122147
Here is an example discovery:
123148

docs/httplug.md

Lines changed: 29 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -5,22 +5,37 @@ Httplug is an abstraction for HTTP clients. There are two main use cases:
55
1. Usage in a project
66
2. Usage in a reusable package
77

8-
In both cases, the client provides a `sendRequest` method to send a PSR-7 `RequestInterface` and returns a PSR-7 `ResponseInterface` or throws an exception that implements `Http\Client\Exception`.
8+
In both cases, the `Http\Client\HttpClient` provides a `sendRequest` method to send a PSR-7 `RequestInterface` and returns a PSR-7 `ResponseInterface`
9+
or throws an exception that implements `Http\Client\Exception`.
10+
11+
There is also the `Http\Client\HttpAsyncClient`, available in [php-http/httplug-async](https://packagist.org/packages/php-http/httplug-async), which provides the `sendAsyncRequest` method to send a request asynchronously and returns a `Http\Client\Promise`.
12+
It can be used later to retrieve a PSR-7 `ResponseInterface` or an exception that implements `Http\Client\Exception`.
913

10-
See the [tutorial](tutorial.md) for a concrete example.
1114

15+
<p class="text-warning">
16+
Contract for the HttpAsyncClient is experimental until [PSR about Promise is released](https://groups.google.com/forum/?fromgroups#!topic/php-fig/wzQWpLvNSjs).
17+
Once it is out, we will use this interface in the main client and deprecate the separated repository.
18+
</p>
19+
20+
See the [tutorial](tutorial.md) for a concrete example.
1221

1322
## Httplug implementations
1423

15-
Httplug implementations typically are either HTTP clients of their own, or they are adapters wrapping existing clients like Guzzle 6. In the latter case, they will depend on the required client implementation, so you only need to require the adapter and not the actual client.
24+
Httplug implementations typically are either HTTP clients of their own, or they are adapters wrapping existing clients like Guzzle 6.
25+
In the latter case, they will depend on the required client implementation, so you only need to require the adapter and not the actual client.
1626

17-
See [packagist](https://packagist.org/providers/php-http/client-implementation) for the full list of implementations.
27+
There are two kind of implementation:
28+
29+
- [php-http/client-implementation](https://packagist.org/providers/php-http/client-implementation), the synchronous implementation that waits for the response / error before returning from the `sendRequest` method.
30+
- [php-http/client-async-implementation](https://packagist.org/providers/php-http/async-client-implementation), the asynchronous implementation that immediately returns a `Http\Client\Promise`, allowing to send several requests in parallel and handling responses later.
31+
32+
Check links above for the full list of implementations.
1833

1934
Note: Until Httplug 1.0 becomes stable, we will focus on the Guzzle6 adapter.
2035

2136
## Usage in a project
2237

23-
When writing an application, you need to require a concrete [client implementation](https://packagist.org/providers/php-http/client-implementation).
38+
When writing an application, you need to require a concrete [implementation](https://packagist.org/providers/php-http/client-implementation).
2439

2540
See [virtual package](virtual-package.md) for more information on the topic of working with Httplug implementations.
2641

@@ -29,17 +44,20 @@ See [virtual package](virtual-package.md) for more information on the topic of w
2944

3045
In many cases, packages are designed to be reused from the very beginning. For example, API clients are usually used in other packages/applications, not on their own.
3146

32-
In these cases, they should **not rely on a concrete implementation** (like Guzzle 6), but only require any implementation of Httplug. Httplug uses the concept of virtual packages. Instead of depending on only the interfaces, which would be missing an implementation, or depending on one concrete implementation, you should depend on the virtual package `php-http/client-implementation`. There is no package with that name, but all clients and adapters implementing Httplug declare that they provide this virtual package.
47+
In these cases, they should **not rely on a concrete implementation** (like Guzzle 6), but only require any implementation of Httplug.
48+
Httplug uses the concept of virtual packages. Instead of depending on only the interfaces, which would be missing an implementation,
49+
or depending on one concrete implementation, you should depend on the virtual package `php-http/client-implementation` or `php-http/async-client-implementation`.
50+
There is no package with that name, but all clients and adapters implementing Httplug declare that they provide one of this virtual package or both.
3351

3452
You need to edit the `composer.json` of your package to add the virtual package. For development (installing the package standalone, running tests), add a concrete implementation in the `require-dev` section to make the project installable:
3553

3654
``` json
3755
...
38-
"require": {
39-
"php-http/client-implementation": "^1.0"
40-
},
41-
"require-dev": {
42-
"php-http/guzzle6-adapter": "^1.0"
56+
"require": {
57+
"php-http/client-implementation": "^1.0"
58+
},
59+
"require-dev": {
60+
"php-http/guzzle6-adapter": "^1.0"
4361
},
4462
...
4563
```

docs/tutorial.md

Lines changed: 118 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -32,13 +32,127 @@ require('vendor/autoload.php');
3232
TODO: create client instance with discovery and do some requests
3333
```
3434

35-
## Handling errors
35+
## Using an asynchronous client
3636

37-
TODO: explain how to handle exceptions, distinction between network exception and HttpException.
37+
Asynchronous client accepts a PSR-7 `RequestInterface` and returns a `Http\Client\Promise` :
38+
39+
```php
40+
use Http\Discovery\HttpAsyncClientDiscovery;
41+
42+
$httpAsyncClient = HttpAsyncClientDiscovery::find();
43+
$promise = $httpAsyncClient->sendAsyncRequest($request);
44+
```
45+
46+
### Using callback system
47+
48+
This promise allows you to add callbacks for when the response is available or an errors happens by using the then method:
49+
50+
```php
51+
$promise->then(function (ResponseInterface $response) {
52+
// onFulfilled callback
53+
echo 'The response is available';
54+
55+
return $response;
56+
}, function (Exception $e) {
57+
// onRejected callback
58+
echo 'An error happens';
59+
60+
throw $e;
61+
});
62+
```
63+
64+
This method will return another promise so you can manipulate the response and/or exception and
65+
still provide a way to interact with this object for your users:
66+
67+
```php
68+
$promise->then(function (ResponseInterface $response) {
69+
// onFulfilled callback
70+
echo 'The response is available';
71+
72+
return $response;
73+
}, function (Exception $e) {
74+
// onRejected callback
75+
echo 'An error happens';
76+
77+
throw $e;
78+
})->then(function (ResponseInterface $response) {
79+
echo 'Response stil available';
80+
81+
return $response;
82+
}, function (Exception $e) {
83+
throw $e
84+
});
85+
```
86+
87+
In order to achieve the chain callback, if you read previous examples carefully, callbacks provided to the `then` method __must__
88+
return a PSR-7 `ResponseInterface` or throw a `Http\Client\Exception`. For both of the callbacks, if it returns a PSR-7 `ResponseInterface`
89+
it will call the `onFulfilled` callback for the next element in the chain, if it throws a `Http\Client\Exception` it will call the `onRejected`
90+
callback.
91+
92+
i.e. you can inverse the behavior of a call:
93+
94+
```php
95+
$promise->then(function (ResponseInterface $response) use($request) {
96+
// onFulfilled callback
97+
echo 'The response is available, but it\'s not ok...';
98+
99+
throw new HttpException('My error message', $request, $response);
100+
}, function (Exception $e) {
101+
// onRejected callback
102+
echo 'An error happens, but it\'s ok...';
103+
104+
return $exception->getResponse();
105+
});
106+
```
107+
108+
Calling the `wait` method on the promise will wait for the response or exception to be available and invoke callback provided in the `then` method.
109+
110+
### Using the promise directly
38111

39-
## Doing parallel requests
112+
If you don't want to use the callback system, you can also get the state of the promise with `$promise->getState()` will return of one `Promise::PENDING`, `Promise::FULFILLED` or `Promise::REJECTED`
40113

41-
TODO explain sendRequests and how to work with BatchResult and BatchException
114+
Then you can get the response of the promise if it's in `FULFILLED` state with `$promise->getResponse()` call or
115+
get the error of the promise if it's in `REJECTED` state with `$promise->getRequest()` call
116+
117+
### Example
118+
119+
Here is a full example of a classic usage when using the `sendAsyncRequest` method:
120+
121+
```php
122+
use Http\Discovery\HttpAsyncClientDiscovery;
123+
124+
$httpAsyncClient = HttpAsyncClientDiscovery::find();
125+
126+
$promise = $httpAsyncClient->sendAsyncRequest($request);
127+
$promise->then(function (ResponseInterface $response) {
128+
echo 'The response is available';
129+
130+
return $response;
131+
}, function (Exception $e) {
132+
echo 'An error happens';
133+
134+
throw $e;
135+
});
136+
137+
// Do some stuff not depending on the response, calling another request, etc ..
138+
...
139+
140+
// We need now the response for our final treatment
141+
$promise->wait();
142+
143+
if (Promise::FULFILLED === $promise->getState()) {
144+
$response = $promise->getResponse();
145+
} else {
146+
throw new \Exception('Response not available');
147+
}
148+
149+
// Do your stuff with the response
150+
...
151+
```
152+
153+
## Handling errors
154+
155+
TODO: explain how to handle exceptions, distinction between network exception and HttpException.
42156

43157

44158
## Writing a reusable package

0 commit comments

Comments
 (0)