PHP code example of gousto / replay

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

    

gousto / replay example snippets




use Gousto\Replay\Replay;

try {

    $result = Replay::retry(3, function() {
       return Http::get('example.com'); 
    }, 50);
    
    Log::info("All good");
} catch(\Gousto\Replay\RetryLogicException $e) {
    \Log::error("After 3 times the function still error out!");
}




use Gousto\Replay\Replay;

$replay = Replay::times(3, function() {

    throw new LogicException();
  
}, 10);

$replay->onRetry(function(Exception $e, Replay $replay) {
   $replay->setDelay($replay->getDelay() * 2); 
});

// play the strategy!
$replay->play();



use Gousto\Replay\Replay;

// Will throw LogicException and not retry
Replay::retry(3, function() {

    throw new LogicException();
  
}, 0, [RuntimeException::class]);

use Gousto\Replay\Replay;

Replay::retry(1, function() {

    throw new Exception();
  
}, 0, [Exception::class]);

use Gousto\Replay\Replay;

$replay = Replay::times(1, function() {

    throw new Exception();
  
}, 0, [Exception::class]);

$replay->play();

use Gousto\Replay\Replay;

$replay = Replay::times(2, function() {

    throw new Exception();
  
}, 0, [Exception::class]);

$result = $replay->play(true); // $result instanceof RetryLogicException

$replay->play(); // throw RetryLogicException

use Gousto\Replay\Replay;

$counter = 0;
$replay = Replay::times(3, function() use (&$counter) {
    $counter++;
    if ($counter === 3) {
        return $counter;
    }
    throw new Exception("Error"); 
});

// WILL LOG:
// Attempt 1: Failed
// Attempt 2: Failed
$replay->onRetry(function(Exception $exception, Replay $replay) {
   Log::error("Attempt {$replay->attempts()}: Failed"); 
});

try {
    $replay->play();
} catch(\Gousto\Replay\RetryLogicException $e) {
    
}

use Gousto\Replay\Replay;

$replay = Replay::times(3, function() {

    throw new Exception();
  
}, 0, [Exception::class]);

$replay->next(); // 1 attempt
$replay->next(); // 2 attempts
$replay->next(); // Throw RetryLogicException

use Gousto\Replay\Replay;

$replay = Replay::times(3, function() {

    throw new Exception();
  
}, 0, [Exception::class]);

$replay->next();
$replay->attempts(); // 1

$replay->next();
$replay->attempts(); // 2

$replay = Replay::times(4, function() {

    return 10;
  
}, 0, [Exception::class]);

$result = $replay->play(); // 10

$replay->isErrored(); // False