-
-
Notifications
You must be signed in to change notification settings - Fork 8
Overview
The easiest way to understand Fetch is to see the overall shape of the code first.
use GT\Fetch\Http;
$http = new Http();use GT\Http\Response;
$http->fetch("https://api.github.com/orgs/phpgt/repos")
->then(function(Response $response) {
if(!$response->ok) {
throw new RuntimeException("Unexpected status: $response->status");
}
return $response->json();
})
->then(function($json) {
echo "Repository count: ", count($json->getPrimitiveValue()), PHP_EOL;
});$http->wait();This is the basic pattern we will use throughout the rest of the documentation:
- create one
Httpobject - queue one or more requests
- attach
then()andcatch()handlers as needed - call
wait()orall()
The first promise returned from fetch() resolves with a GT\Http\Response. From there we can inspect headers and status immediately, and then choose how to read the body.
The most common body helpers are:
$response->text()$response->json()$response->blob()$response->formData()
Each of these returns another Promise. This means we can keep chaining work in a natural way.
$http->fetch("https://example.com/data.json")
->then(function(Response $response) {
return $response->json();
})
->then(function($json) {
// Work with decoded JSON here.
});If we prefer a blocking flow, we can use awaitFetch() and the matching await... methods on the response body:
$response = $http->awaitFetch("https://example.com/data.json");
$json = $response->awaitJson();One of the most useful parts of this library is that we can queue multiple requests on the same Http object before calling wait().
$http->fetch("https://example.com/a.json");
$http->fetch("https://example.com/b.json");
$http->fetch("https://example.com/c.json");
$http->wait();Here we can see the intent clearly: set up all of the work first, then wait for it to complete. This is often much easier to read than deeply nested synchronous request code.
In the next section we will look at constructing Http objects.
PHP.GT/Fetch is a separately maintained component of PHP.GT/WebEngine.