phpgt / fetch
异步HTTP客户端,使用承诺(promises)。
v1.2.0
2024-01-31 09:53 UTC
Requires
- php: >=8.1
- ext-curl: *
- ext-json: *
- phpgt/async: ^1.0
- phpgt/curl: ^3.1.1
- phpgt/http: ^1.3
- phpgt/json: ^1.2
- phpgt/promise: ^2.2.3
- phpgt/propfunc: ^1.0
Requires (Dev)
- phpmd/phpmd: ^2.13
- phpstan/phpstan: ^1.10
- phpunit/phpunit: ^10.2
- squizlabs/php_codesniffer: ^3.7
This package is auto-updated.
Last update: 2024-08-30 01:23:11 UTC
README
异步HTTP客户端,实现Fetch标准,该标准定义了请求、响应以及将它们关联起来的过程:获取(fetching)。
另请参阅,作为所有现代浏览器标准的JavaScript实现。
示例用法:使用fetch
并行计算多个HTTP请求
<?php $http = new Gt\Fetch\Http(); // Rather than creating the request now, `fetch` returns a Promise, // for later resolution with the BodyResponse. $http->fetch("http://example.com/api/something.json") ->then(function(BodyResponse $response) { // The first Promise resolves as soon as a response is received, even before // the body's content has completed downloading. if(!$response->ok) { echo "Looks like there was a problem. Status code: " . $response->getStatusCode() . PHP_EOL; return null; } // Within this Promise callback, you have access to the body stream, but // to access the contents of the whole body, return a new Promise here: return $response->json(); }) ->then(function(Json $json) { // The second Promise resolves once the whole body has completed downloading. echo "Got JSON result length " . count($json->results) . PHP_EOL; // Notice that type-safe getters are available on all Json objects: echo "Name of first result: " . $json->results[0]->getString("name") . PHP_EOL; }); // A third request is made here to show a different type of body response: $http->fetch("http://example.com/something.jpg") ->then(function(BodyResponse $response) { return $response->blob(); }) ->then(function($blob) { echo "Got JPG blob. Saving file." . PHP_EOL; file_put_contents("/tmp/something.jpg", $blob); }); // Once all Promises are registered, all HTTP requests can be initiated in // parallel, with the callback function triggered when they are all complete. $http->all()->then(function() { echo "All HTTP calls have completed!" . PHP_EOL; });
更多示例,请查看示例目录中的代码。