-
-
Notifications
You must be signed in to change notification settings - Fork 8
Usage examples
The repository contains a small example/ directory with runnable scripts. This page walks through them and explains what each one demonstrates.
If you prefer to learn by reading complete scripts rather than isolated snippets, this is the best place to start.
File: example/01-basic-fetch.php
This example performs a simple GET request to the GitHub API and then decodes the JSON response.
Here we can see the standard fetch workflow very clearly:
- queue the request with
fetch() - inspect the
Response - decode the body with
json() - finish the request batch with
wait()
use GT\Fetch\Http;
use GT\Http\Response;
use GT\Json\JsonKvpObject;
use GT\Json\JsonPrimitive\JsonArrayPrimitive;
$http = new Http();
$http->fetch("https://api.github.com/orgs/phpgt/repos")
->then(function(Response $response) {
echo "Got a response. Processing JSON... ", PHP_EOL;
if(!$response->ok) {
throw new RuntimeException("Can't retrieve Github's API on $response->uri");
}
return $response->json();
})
->then(function(JsonArrayPrimitive $json) {
echo "SUCCESS: Json promise resolved!", PHP_EOL, PHP_EOL;
echo "PHP.Gt has the following repositories: ";
$repoList = [];
/** @var JsonKvpObject $item */
foreach($json->getPrimitiveValue() as $item) {
array_push($repoList, $item->getString("name"));
}
echo wordwrap(implode(", ", $repoList)) . ".";
echo PHP_EOL, PHP_EOL;
})
->catch(function(Throwable $reason) {
echo "There was an error!",
PHP_EOL,
get_class($reason),
" - ",
$reason->getMessage(),
" ",
$reason->getFile(),
":", $reason->getLine(),
PHP_EOL, PHP_EOL;
});
$http->wait();File: example/02-post-request.php
This example posts FormData to Postman Echo and then reads the JSON representation of what the server received.
It shows:
- setting the request method
- sending a request body
- decoding JSON in the response
- working with type-safe getters from
GT\Json
use GT\Fetch\Http;
use GT\Http\FormData;
use GT\Http\Response;
use GT\Json\JsonObject;
$formData = new FormData();
$formData->set("name", "Mark Zuckerberg");
$formData->set("dob", "1984-05-14");
$formData->set("email", "zuck@fb.com");
$http = new Http();
$http->fetch("https://postman-echo.com/post", [
"method" => "POST",
"body" => $formData,
])
->then(function(Response $response) {
if(!$response->ok) {
throw new RuntimeException("Error posting to Postman Echo.");
}
return $response->json();
})
->then(function(JsonObject $json) {
echo "The Postman Echo server received the following form fields:";
echo PHP_EOL;
$formObject = $json->getObject("form");
foreach($formObject->asArray() as $key => $value) {
echo "$key = $value" . PHP_EOL;
}
});
$http->wait();File: example/03-download-jpg.php
This example fetches a binary response from Cat as a Service and saves it to disk.
It demonstrates:
- checking response headers
- converting the body to a
Blob - handling binary downloads
use GT\Fetch\Http;
use GT\Http\Blob;
use GT\Http\Response;
$http = new Http();
$http->fetch("https://cataas.com/cat")
->then(function(Response $response) {
if(!$response->ok) {
throw new RuntimeException("Error getting a cat. (ERROR $response->status)");
}
echo "Cat as a Service responded with a binary file with the following attributes:" . PHP_EOL;
echo "Response size: " . $response->getHeaderLine("Content-Length") . PHP_EOL;
echo "File type: " . $response->getHeaderLine("Content-Type") . PHP_EOL;
return $response->blob();
})
->then(function(Blob $blob) {
$file = new SplFileObject("/tmp/cat.jpg", "w");
$bytesWritten = $file->fwrite($blob);
echo "Written $bytesWritten bytes." . PHP_EOL;
echo "Photo written to " . $file->getPathname() . PHP_EOL;
});
$http->wait();File: example/04-multiple-concurrent-fetch.php
This script queues several unrelated requests and lets them resolve together.
It is a good example of the main async advantage of the library: we can declare all of the work first and then allow the internal loop to complete it.
File: example/05-upload-file.php
Here we build a FormData object that includes a file upload. The file is posted to Postman Echo, which returns the uploaded content in the response body.
This demonstrates:
- multipart form uploads
- using
FormDatawith files - handling the JSON response afterwards
File: example/06-request-object.php
This example shows that fetch() does not need to be given a URL string. We can pass a PSR-7 RequestInterface instead.
use GT\Fetch\Http;
use GT\Http\Header\RequestHeaders;
use GT\Http\Request;
use GT\Http\Response;
use GT\Http\Uri;
$request = new Request(
"GET",
new Uri("https://api.github.com/orgs/phpgt/repos"),
new RequestHeaders()
);
$http = new Http();
$http->fetch($request)
->then(function(Response $response) {
echo "Status: ", $response->status, PHP_EOL;
return $response->json();
})
->then(function($json) {
echo "Received ", count($json->getPrimitiveValue()), " repositories.", PHP_EOL;
});
$http->wait();File: example/07-abort-request.php
This example introduces AbortController. It starts a request, aborts it, and then finishes the batch.
use GT\Fetch\AbortController;
use GT\Fetch\Http;
$http = new Http();
$controller = new AbortController();
$http->fetch("https://example.com/large-file.zip", [
"signal" => $controller->signal,
]);
$controller->abort();
$http->wait();The point of the example is the control flow rather than the output. When we need to stop one request out of several, or stop several with one shared signal, this is the mechanism to use.
PHP.GT/Fetch is a separately maintained component of PHP.GT/WebEngine.