PHP code example of rasuvaeff / circuit-breaker

1. Go to this page and download the library: Download rasuvaeff/circuit-breaker 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 / circuit-breaker example snippets


use Psr\Http\Client\ClientExceptionInterface;
use Rasuvaeff\CircuitBreaker\BreakerConfig;
use Rasuvaeff\CircuitBreaker\CircuitBreaker;
use Rasuvaeff\CircuitBreaker\CircuitState;
use Rasuvaeff\CircuitBreaker\InMemoryStorage;
use Rasuvaeff\Duration\Duration;

$cb = new CircuitBreaker(
    config: BreakerConfig::forRemoteApi(
        name: 'stripe',
        failures: 5, window: 10, within: Duration::seconds(60), // 5 of the last 10 calls within 60s
        cooldown: Duration::seconds(30),   // how long Open lasts before a probe is allowed
        // Classify only exceptions that indicate a downstream failure.
        isFailure: static fn(\Throwable $e): bool => $e instanceof ClientExceptionInterface,
    ),
    storage: new InMemoryStorage(), // single process only: ApcuStorage / RedisStorage for FPM workers
    // clock: defaults to Clock\SystemClock
);

$charge = $cb->call(
    callback: static fn(): mixed => $stripe->charges->create([/* ... */]),
    fallback: static fn(\Throwable $e): mixed => ChargeResult::queuedForRetry(),
);

if ($cb->state() === CircuitState::Open) {
    // show a degraded UI without attempting the call
}

use Rasuvaeff\CircuitBreaker\Ratio;

$config = new BreakerConfig(
    name: 'stripe',
    failureThreshold: Ratio::of(failures: 5, window: 10, within: Duration::seconds(60)),
    cooldown: Duration::seconds(30),
    successThreshold: 3,               // consecutive probe successes to close again
    isFailure: static fn(\Throwable $e): bool => $e instanceof ClientExceptionInterface,
);

use Predis\Client;
use Rasuvaeff\CircuitBreaker\Redis\PredisScriptRunner;
use Rasuvaeff\CircuitBreaker\RedisStorage;

$storage = new RedisStorage(new PredisScriptRunner(new Client(['host' => '127.0.0.1'])));

use Rasuvaeff\CircuitBreaker\Redis\PhpRedisScriptRunner;

$redis = new \Redis();
$redis->connect('127.0.0.1');
$storage = new RedisStorage(new PhpRedisScriptRunner($redis));

use Rasuvaeff\CircuitBreaker\ApcuStorage;

$storage = new ApcuStorage();

use Psr\Http\Client\ClientExceptionInterface;
use Rasuvaeff\Context\ContextCancelledException;
use Rasuvaeff\Context\ContextExpiredException;

$config = new BreakerConfig(
    // ...
    isFailure: static fn(\Throwable $e): bool => match (true) {
        $e instanceof ContextCancelledException, // the caller gave up
        $e instanceof ContextExpiredException => false, // the caller's budget ran out
        default => $e instanceof ClientExceptionInterface,
    },
);

use Rasuvaeff\CircuitBreaker\CircuitSnapshotObserver;
use Rasuvaeff\CircuitBreaker\CircuitTransition;
use Rasuvaeff\CircuitBreaker\Metrics;

final class OpenGauge implements CircuitSnapshotObserver
{
    public function onTransition(CircuitTransition $transition): void
    {
        $this->set($transition->breakerName(), $transition->to() === CircuitState::Open);
    }

    public function onSnapshot(string $breakerName, Metrics $metrics): void
    {
        $this->set($breakerName, $metrics->state() === CircuitState::Open);
    }

    private function set(string $breakerName, bool $open): void { /* gauge->set(...) */ }
}

$cb = new CircuitBreaker(config: $config, storage: $storage, observer: new OpenGauge());
$cb->publishState(); // the series exists from now on, even if the breaker never trips

use Psr\Log\LoggerInterface;
use Rasuvaeff\CircuitBreaker\CircuitBreaker;
use Rasuvaeff\CircuitBreaker\LoggingCircuitObserver;

$cb = new CircuitBreaker(
    config: $config,
    storage: $storage,
    observer: new LoggingCircuitObserver($logger), // any PSR-3 logger
);