React Adapter¶
An HTTPlug adapter for the React Http client.
Installation¶
Use Composer to install the React adapter. It will also install React as it’s a dependency.
$ composer require php-http/react-adapter
This client does not come with a PSR-7 implementation out of the box, so you have to install one as well (for example Guzzle PSR-7):
$ composer require guzzlehttp/psr7
In order to provide full interoperability, message implementations are accessed through factories. Message factories for Laminas Diactoros (and its abandoned predecessor Zend Diactoros), Guzzle PSR-7 and `Slim Framework`_ are available in the message component:
$ composer require php-http/message
Alternatively you can install the discovery layer to be able to automatically find installed resources, like factories:
$ composer require php-http/discovery
Usage¶
If you need control on the React instances, you can inject them during initialization:
use Http\Adapter\React\Client;
$systemDnsConfig = React\Dns\Config\Config::loadSystemConfigBlocking();
if (!$config->nameservers) {
$config->nameservers[] = '8.8.8.8';
}
$dnsResolverFactory = new React\Dns\Resolver\Factory();
$dnsResolver = $factory->create($config);
$connector = new React\Socket\Connector([
'dns' => $dnsResolver,
]);
$browser = new React\Http\Browser($connector);
$adapter = new Client($browser);
You can also use a ReactFactory
in order to initialize React instances:
use Http\Adapter\React\ReactFactory;
$reactHttp = ReactFactory::buildHttpClient();
Then you can use the adapter to send synchronous requests:
use GuzzleHttp\Psr7\Request;
$request = new Request('GET', 'http://httpbin.org');
// Returns a Psr\Http\Message\ResponseInterface
$response = $adapter->sendRequest($request);
Or send asynchronous ones:
use GuzzleHttp\Psr7\Request;
$request = new Request('GET', 'http://httpbin.org');
// Returns a Http\Promise\Promise
$promise = $adapter->sendAsyncRequest(request);
Note that since v4 calling wait on HttpPromisePromise is expected to run inside a fiber:
use function React\Async\async;
async(static function () {
// Returns a Http\Promise\Promise
$promise = $adapter->sendAsyncRequest(request);
// Returns a Psr\Http\Message\ResponseInterface
$response = $promise->wait();
})();
Further reading¶
Use plugins to customize the way HTTP requests are sent and responses processed by following redirects, adding Authentication or Cookie headers and more.
Learn how you can decouple your code from any PSR-7 implementation by using the HTTP factories.
Read more about promises when using asynchronous requests.