Skip to content

Commit

Permalink
Merge pull request #21 from joelwurtz/feature/async
Browse files Browse the repository at this point in the history
Add documentation for async client
  • Loading branch information
dbu committed Nov 9, 2015
2 parents 6906a2b + 1ff4919 commit ae9d39c
Show file tree
Hide file tree
Showing 3 changed files with 177 additions and 20 deletions.
35 changes: 30 additions & 5 deletions docs/discovery.md
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,7 @@ composer require "php-http/discovery"

## HTTP Client Discovery

This type of discovery finds installed HTTP Clients.
This type of discovery finds an HTTP Client implementation.

``` php
use Http\Client\HttpClient;
Expand All @@ -33,7 +33,7 @@ class MyClass
protected $httpClient;

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

## HTTP Async Client Discovery

This type of discovery finds a HTTP Async Client implementation.

``` php
use Http\Client\HttpAsyncClient;
use Http\Discovery\HttpAsyncClientDiscovery;

class MyClass
{
/**
* @var HttpAsyncClient
*/
protected $httpAsyncClient;

/**
* @param HttpAsyncClient|null $httpAsyncClient Client to do HTTP requests, if not set, autodiscovery will be used to find an asynchronous client.
*/
public function __construct(HttpAsyncClient $httpAsyncClient = null)
{
$this->httpAsyncClient = $httpAsyncClient ?: HttpAsyncClientDiscovery::find();
}
}
```

## PSR-7 Message Factory Discovery

This type of discovery finds installed [PSR-7](http://www.php-fig.org/psr/psr-7/) Message implementations and their [factories](message-factory.md).
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.

``` php
use Http\Message\MessageFactory;
Expand All @@ -71,7 +95,7 @@ class MyClass

## PSR-7 URI Factory Discovery

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

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

### Writing your own discovery

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.
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.
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.

Here is an example discovery:

Expand Down
40 changes: 29 additions & 11 deletions docs/httplug.md
Original file line number Diff line number Diff line change
Expand Up @@ -5,22 +5,37 @@ Httplug is an abstraction for HTTP clients. There are two main use cases:
1. Usage in a project
2. Usage in a reusable package

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`.
In both cases, the `Http\Client\HttpClient` 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`.

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`.
It can be used later to retrieve a PSR-7 `ResponseInterface` or an exception that implements `Http\Client\Exception`.

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

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

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

## Httplug implementations

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.
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.

See [packagist](https://packagist.org/providers/php-http/client-implementation) for the full list of implementations.
There are two kind of implementation:

- [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.
- [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.

Check links above for the full list of implementations.

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

## Usage in a project

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

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

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

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.

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.
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` or `php-http/async-client-implementation`.
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.

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:

``` json
...
"require": {
"php-http/client-implementation": "^1.0"
},
"require-dev": {
"php-http/guzzle6-adapter": "^1.0"
"require": {
"php-http/client-implementation": "^1.0"
},
"require-dev": {
"php-http/guzzle6-adapter": "^1.0"
},
...
```
Expand Down
122 changes: 118 additions & 4 deletions docs/tutorial.md
Original file line number Diff line number Diff line change
Expand Up @@ -32,13 +32,127 @@ require('vendor/autoload.php');
TODO: create client instance with discovery and do some requests
```

## Handling errors
## Using an asynchronous client

TODO: explain how to handle exceptions, distinction between network exception and HttpException.
Asynchronous client accepts a PSR-7 `RequestInterface` and returns a `Http\Client\Promise` :

```php
use Http\Discovery\HttpAsyncClientDiscovery;

$httpAsyncClient = HttpAsyncClientDiscovery::find();
$promise = $httpAsyncClient->sendAsyncRequest($request);
```

### Using callback system

This promise allows you to add callbacks for when the response is available or an errors happens by using the then method:

```php
$promise->then(function (ResponseInterface $response) {
// onFulfilled callback
echo 'The response is available';

return $response;
}, function (Exception $e) {
// onRejected callback
echo 'An error happens';

throw $e;
});
```

This method will return another promise so you can manipulate the response and/or exception and
still provide a way to interact with this object for your users:

```php
$promise->then(function (ResponseInterface $response) {
// onFulfilled callback
echo 'The response is available';

return $response;
}, function (Exception $e) {
// onRejected callback
echo 'An error happens';

throw $e;
})->then(function (ResponseInterface $response) {
echo 'Response stil available';

return $response;
}, function (Exception $e) {
throw $e
});
```

In order to achieve the chain callback, if you read previous examples carefully, callbacks provided to the `then` method __must__
return a PSR-7 `ResponseInterface` or throw a `Http\Client\Exception`. For both of the callbacks, if it returns a PSR-7 `ResponseInterface`
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`
callback.

i.e. you can inverse the behavior of a call:

```php
$promise->then(function (ResponseInterface $response) use($request) {
// onFulfilled callback
echo 'The response is available, but it\'s not ok...';

throw new HttpException('My error message', $request, $response);
}, function (Exception $e) {
// onRejected callback
echo 'An error happens, but it\'s ok...';

return $exception->getResponse();
});
```

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.

### Using the promise directly

## Doing parallel requests
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`

TODO explain sendRequests and how to work with BatchResult and BatchException
Then you can get the response of the promise if it's in `FULFILLED` state with `$promise->getResponse()` call or
get the error of the promise if it's in `REJECTED` state with `$promise->getRequest()` call

### Example

Here is a full example of a classic usage when using the `sendAsyncRequest` method:

```php
use Http\Discovery\HttpAsyncClientDiscovery;

$httpAsyncClient = HttpAsyncClientDiscovery::find();

$promise = $httpAsyncClient->sendAsyncRequest($request);
$promise->then(function (ResponseInterface $response) {
echo 'The response is available';

return $response;
}, function (Exception $e) {
echo 'An error happens';

throw $e;
});

// Do some stuff not depending on the response, calling another request, etc ..
...

// We need now the response for our final treatment
$promise->wait();

if (Promise::FULFILLED === $promise->getState()) {
$response = $promise->getResponse();
} else {
throw new \Exception('Response not available');
}

// Do your stuff with the response
...
```

## Handling errors

TODO: explain how to handle exceptions, distinction between network exception and HttpException.


## Writing a reusable package
Expand Down

0 comments on commit ae9d39c

Please sign in to comment.