wp-oop / http-client
A PSR-18 wrapper for the WordPress HTTP API
Installs: 1 504
Dependents: 0
Suggesters: 0
Security: 0
Stars: 3
Watchers: 1
Forks: 0
Open Issues: 0
Requires
- php: ^7.4 | ^8.0
- psr/http-client: ^1.0
- psr/http-factory: ^1.0.2
- psr/http-factory-implementation: *
Requires (Dev)
- brain/monkey: ^2.6.1
- johnpbloch/wordpress-core: 6.3
- nyholm/psr7: ^1.7
- php-stubs/wordpress-stubs: 6.3
- phpunit/phpunit: ^9.0@stable
- slevomat/coding-standard: ^6.0
- vimeo/psalm: ^5.0
- webmozart/path-util: ^2.3@stable
Suggests
- nyholm/psr7: A slim and efficient PSR-7 and PSR-17 implementation
This package is auto-updated.
Last update: 2024-10-30 02:16:26 UTC
README
A PSR-18 wrapper for the WordPress HTTP API.
Usage
use Psr\Http\Client\ClientExceptionInterface; use Psr\Http\Message\RequestFactoryInterface; use Psr\Http\Message\ResponseFactoryInterface; use WpOop\HttpClient\Client; /** @var RequestFactoryInterface $requestFactory */ /** @var ResponseFactoryInterface $responseFactory */ // Set up the client with WP request options // https://developer.wordpress.org/reference/classes/wp_http/request/ $client = new Client( // Default args to WP_Http::request() [ 'redirection' => 2, 'timeout' => 60, ], $responseFactory, // Path to proxy file dir to enable response streaming. // If null, will buffer in memory instead. get_temp_dir() ); // Create a PSR-7 request in any way you want, for example via a PSR-17 factory $request = $requestFactory->createRequest('GET', 'http://somesite.com/api'); try { // Send a request as usual, consuming a familiar PSR-18 interface $response = $client->sendRequest($request); } catch (ClientExceptionInterface $e) { // Handle PSR-18 exceptions }
Since this is a PSR-18-compliant implementation, you can consume it in the way you would any other.
To set it up, pass a map of WP request options, and a PSR-17 response factory. This approach facilitates decoupling from any concrete PSR-7 implementation.
You can use any PSR-17 implementation or PSR-7 implementations. I suggest the slim and efficient nyholm/psr7, which conveniently implements both.
Limitations
Currently only throws ClientExceptionInterface
, as it is unable to reliably determine whether a network or
another specific kind of problem has occurred from the error value returned by wp_remote_request()
.