PHP code example of philiprehberger / php-retry
1. Go to this page and download the library: Download philiprehberger/php-retry library . Choose the download type require .
2. Extract the ZIP file and open the index.php.
3. Add this code to the index.php.
<?php
require_once('vendor/autoload.php');
/* Start to develop here. Best regards https://php-download.com/ */
philiprehberger / php-retry example snippets
use PhilipRehberger\Retry\Retry;
$result = Retry::times(3)->run(function () {
return file_get_contents('https://api.example.com/data');
});
echo $result->value; // The response body
echo $result->attempts; // Number of attempts made
echo $result->totalTimeMs; // Total time spent in milliseconds
$result = Retry::times(5)
->backoff(baseMs: 100, maxMs: 5000)
->jitter()
->run(fn () => $httpClient->get('/unstable-endpoint'));
$result = Retry::times(3)
->linear(delayMs: 200)
->run(fn () => $api->call());
$result = Retry::times(4)
->constant(delayMs: 500)
->run(fn () => $service->fetch());
$result = Retry::times(5)
->onlyIf(fn (\Throwable $e) => $e instanceof ConnectionException)
->run(fn () => $db->query($sql));
$result = Retry::times(5)
->except(ValidationException::class, AuthenticationException::class)
->run(fn () => $api->submit($data));
$retry = Retry::times(5)
->shouldRetry(function (\Throwable $e, int $attempt): bool {
// Stop retrying after attempt 3 for rate-limit errors
if ($e instanceof RateLimitException && $attempt >= 3) {
return false;
}
return true;
})
->run(fn () => $api->request());
$result = Retry::times(5)
->retryOnlyOn(ConnectionException::class, TimeoutException::class)
->run(fn () => $httpClient->get('/endpoint'));
$retry = Retry::times(5);
$result = $retry->run(fn () => $service->call());
echo $retry->getAttempts(); // e.g. 3
$result = Retry::times(100)
->constant(delayMs: 50)
->maxDuration(ms: 2000)
->run(fn () => $service->call());
$result = Retry::forever()
->backoff(baseMs: 100, maxMs: 30000)
->jitter()
->maxDuration(ms: 60000)
->run(fn () => $queue->consume());
$result = Retry::times(5)
->backoff(baseMs: 100)
->beforeRetry(function (int $attempt, \Throwable $e) {
logger()->warning("Retry attempt {$attempt}: {$e->getMessage()}");
})
->afterRetry(function (int $attempt, ?\Throwable $e) {
if ($e === null) {
logger()->info("Succeeded on attempt {$attempt}");
}
})
->run(fn () => $api->request());
$result = Retry::times(5)
->backoff(baseMs: 100)
->onSuccess(function (RetryResult $r) {
logger()->info("Succeeded after {$r->attempts} attempt(s)");
})
->run(fn () => $api->request());
$result = Retry::times(3)->run(fn () => $service->call());
if ($result->wasRetried()) {
logger()->warning("Operation bash
composer