1. Go to this page and download the library: Download rasuvaeff/resilience 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/ */
rasuvaeff / resilience example snippets
doc-exec
use Rasuvaeff\Bulkhead\InMemoryBulkheadStore;
use Rasuvaeff\Bulkhead\SharedBulkhead;
use Rasuvaeff\CircuitBreaker\BreakerConfig;
use Rasuvaeff\CircuitBreaker\CircuitBreaker;
use Rasuvaeff\CircuitBreaker\CircuitOpenException;
use Rasuvaeff\CircuitBreaker\Clock\SystemClock;
use Rasuvaeff\CircuitBreaker\InMemoryStorage;
use Rasuvaeff\CircuitBreaker\Ratio;
use Rasuvaeff\Duration\Duration;
use Rasuvaeff\Resilience\Pipeline;
use Rasuvaeff\Retry\Retry;
// Configure the leaves as usual - the pipeline takes them ready-made and
// knows nothing about stores, backends, or policies.
$pipeline = Pipeline::for('billing')
->bulkhead(new SharedBulkhead(
name: 'billing',
maxConcurrent: 2,
store: new InMemoryBulkheadStore(),
lease: Duration::seconds(5),
maxWait: Duration::zero(),
))
->retry(
Retry::new()
->maxAttempts(maxAttempts: 3)
->withImmediate(),
)
->circuitBreaker(new CircuitBreaker(
config: new BreakerConfig(
name: 'billing',
failureThreshold: Ratio::of(failures: 5, window: 10, within: Duration::seconds(60)),
cooldown: Duration::seconds(30),
successThreshold: 1,
isFailure: static fn(\Throwable $e): bool => $e instanceof \RuntimeException,
),
storage: new InMemoryStorage(),
clock: new SystemClock(),
))
->build(); // immutable, reusable
// A transient failure is retried to success:
$attempt = 0;
$pipeline->call(function () use (&$attempt): string {
if (++$attempt < 2) {
throw new \RuntimeException('transient error');
}
return 'succeeded';
}); // => "succeeded"
$attempt; // => 2
// Optional fallback at the outermost level receives the terminal exception:
$pipeline->call(
callback: static fn(): string => 'primary',
fallback: static fn(\Throwable $e): string => $e instanceof CircuitOpenException ? 'degraded' : 'unexpected',
); // => "primary"