PHP code example of zeusi / circuit-breaker

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

    

zeusi / circuit-breaker example snippets


use Zeusi\CircuitBreaker\CircuitBreaker;
use Zeusi\CircuitBreaker\Configuration;
use Zeusi\CircuitBreaker\HalfOpen\RampPolicy;
use Zeusi\CircuitBreaker\Storage\RedisStorage;

$configuration = new Configuration(
    timeWindow: 60,            // seconds over which calls are counted
    failureRateThreshold: 50,  // percentage of failed calls that opens the circuit
    minimumRequests: 10,       // calls needed in the time window before deciding
    openDuration: 10,          // seconds during which no call is permitted once open
    halfOpenPolicy: RampPolicy::createExponential(duration: 60, initialRatio: 0.01),
);

$breaker = new CircuitBreaker('payments', $configuration, new RedisStorage($redis));

if (!$breaker->acquirePermission()) {
    return ChargeResult::deferred(); // the circuit is open: fall back without calling the service
}

try {
    $result = $paymentGateway->charge($order);
} catch (GatewayUnavailableException $e) {
    $breaker->registerFailure();

    throw $e;
}

$breaker->registerSuccess();

RampPolicy::createExponential(duration: 60, initialRatio: 0.01); // 1%, doubling at regular intervals
RampPolicy::createLinear(duration: 60, initialRatio: 0.01);      // 1%, growing at a constant pace

RampPolicy::createPower(duration: 60, initialRatio: 0.01, exponent: 2); // about 26% half way

use Zeusi\CircuitBreaker\HalfOpen\PermittedCallsPolicy;

PermittedCallsPolicy::createSingleTrial(maxDuration: 30);     // the classic single trial
new PermittedCallsPolicy(maxDuration: 30, permittedCalls: 5); // the first 5 calls

use Zeusi\CircuitBreaker\HalfOpen\RampCurveInterface;

final class SteppedRampCurve implements RampCurveInterface
{
    public function computeAdmissionRatio(float $progress): float
    {
        return $progress < 0.5 ? 0.1 : 0.5; // 10%, then 50% from half way
    }
}

new RampPolicy(duration: 60, curve: new SteppedRampCurve());

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

$storage = new RedisStorage($redis, prefix: 'shop:');

$memcached = new \Memcached();
$memcached->addServer('127.0.0.1', 11211);

$storage = new MemcachedStorage($memcached, prefix: 'shop:');

use Zeusi\CircuitBreaker\Event\CircuitOpened;
use Zeusi\CircuitBreaker\Event\EventInterface;
use Zeusi\CircuitBreaker\Event\EventListenerInterface;

final class CircuitLogger implements EventListenerInterface
{
    public function __construct(private readonly LoggerInterface $logger) {}

    public function handleEvent(EventInterface $event): void
    {
        if ($event instanceof CircuitOpened) {
            $this->logger->warning('Circuit opened', ['service' => $event->getService()]);
        }
    }
}

$breaker = new CircuitBreaker('payments', $configuration, $storage, new CircuitLogger($logger));