wp-oop / http-client
WordPress HTTP API 的 PSR-18 包装器
v0.1.0-alpha1
2023-08-18 14:16 UTC
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-08-30 01:48:21 UTC
README
PSR-18 对 WordPress HTTP API 的包装。
用法
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 }
由于这是一个符合 PSR-18 的实现,您可以使用它就像使用其他任何东西一样。
为了设置它,传递一个 WP 请求选项的映射,以及一个 PSR-17 响应工厂。这种方法有助于与任何具体的 PSR-7 实现解耦。
您可以使用任何 PSR-17 实现或 PSR-7 实现。我建议使用既小巧又高效的 nyholm/psr7,它方便地实现了两者。
限制
目前仅抛出 ClientExceptionInterface
,因为它无法从 wp_remote_request()
返回的错误值中可靠地确定是否发生了网络或其他特定类型的问题。