PHP.GT

Cancelling requests

Long-running downloads are not always supposed to finish. Sometimes the user navigates away, sometimes another request supersedes the first one, and sometimes we only want the fastest result from a group of alternatives.

For those cases, the library supports abort signals.

AbortController

To cancel a request, create an AbortController and pass its signal to the request:

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,
]);

When we decide the request should stop, call abort():

$controller->abort();
$http->wait();

Cancelling one request out of many

If several downloads are happening concurrently, give each one its own controller.

$a = new AbortController();
$b = new AbortController();

$http->fetch("https://example.com/file-a.zip", [
	"signal" => $a->signal,
]);

$http->fetch("https://example.com/file-b.zip", [
	"signal" => $b->signal,
]);

$a->abort();
$http->wait();

Here we can see that only the first request is cancelled.

Cancelling several requests together

If we want a single action to cancel more than one request, reuse the same controller:

$controller = new AbortController();

$http->fetch("https://example.com/a.zip", ["signal" => $controller->signal]);
$http->fetch("https://example.com/b.zip", ["signal" => $controller->signal]);

$controller->abort();
$http->wait();

Comparison with the browser API

The usage pattern is deliberately close to browser fetch:

  • create an AbortController
  • pass signal
  • call abort()

The important difference is in behaviour after cancellation. In browser fetch, aborting produces a well-defined AbortError rejection. In this library, the transfer is stopped through cURL’s progress callback. That means the cancellation mechanism is present, but it is not currently modelled as a dedicated browser-style abort exception.