PHP code example of georgii-web / retry

1. Go to this page and download the library: Download georgii-web/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/ */

    

georgii-web / retry example snippets


use GeorgII\Retry;

// Retry a function 3 times on any exception
$result = Retry::onAnyException(fn() => someOperation());

use GeorgII\Retry;
use GeorgII\RetryEvent;

// Retry a function 2 times, with a small delay and logging events on any exception
$result = Retry::onAnyException(
    attemptCallback: function (RetryEvent $event) {
        // Your code that might fail
       return someOperation($event);
    },
    retryCount: 2,
    retryDelay: 0.1,
    eventCallback: function (RetryEvent $event) {
        var_dump($event->getName());
    }
);

    /**
     * Retry on DB exception alias.
     *
     * @template R
     *
     * @param Closure(RetryEvent): R          $attemptCallback
     * @param positive-int|null               $retryCount
     * @param positive-int|float|Closure|null $retryDelay
     * @param Closure(RetryEvent):void|null   $eventCallback
     *
     * @return R
     */
    public static function onDbException(
        Closure $attemptCallback,
        ?int $retryCount = null,
        int|float|Closure|null $retryDelay = null,
        ?Closure $eventCallback = null,
    ): mixed {
        $retry = new RetryCore();

        return $retry
            ->setRetryExceptions([
                ConnectionLost::class,
            ])
            ->setEventCallback($eventCallback)
            ->setRetryCount($retryCount)
            ->setRetryDelay($retryDelay)
            ->setEventFactory(new RetryEventFactory($retry))
            ->setCheckExactException(false)
            ->handle($attemptCallback);
    }

$users = Retry::onDbException(fn() => $sql->query('SELECT * from users'));