PHP code example of christopheraseidl / circuit-breaker

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

    

christopheraseidl / circuit-breaker example snippets


'notifiers' => [
    'email' => [
        'recipients' => [env('MAIL_FROM_ADDRESS')],
        'from_address' => env('MAIL_FROM_ADDRESS'),
        'from_name' => env('MAIL_FROM_NAME'),
    ],
],

use christopheraseidl\CircuitBreaker\CircuitBreaker;

// Create circuit breaker instance
$breaker = new CircuitBreaker(
    name: 'payment-gateway',
    cache: $cache,        // Must implement CacheContract
    logger: $logger,      // Must implement LoggerContract  
    notifier: $notifier,  // Must implement NotifierContract
    config: [
        'failure_threshold' => 5,
        'window_seconds' => 60,
        'recovery_timeout_seconds' => 300,
    ]
);

// Wrap external service calls
if ($breaker->canAttempt()) {
    try {
        $result = $paymentGateway->charge($amount);
        $breaker->recordSuccess();
        return $result;
    } catch (\Exception $e) {
        $breaker->recordFailure();
        throw $e;
    }
} else {
    throw new ServiceUnavailableException('Payment service temporarily unavailable');
}

use christopheraseidl\CircuitBreaker\CircuitBreakerFactory;

// Using dependency injection
public function __construct(
    private CircuitBreakerFactory $circuitBreakerFactory
) {}

public function processPayment($amount)
{
    $breaker = $this->circuitBreakerFactory->make('payment-service', [
        'failure_threshold' => 3,
        'recovery_timeout_seconds' => 120,
    ]);
    
    if ($breaker->canAttempt()) {
        try {
            $response = Http::timeout(5)->post('https://payments.example.com/charge', [
                'amount' => $amount,
            ]);
            $breaker->recordSuccess();
            return $response->json();
        } catch (\Exception $e) {
            $breaker->recordFailure();
            return ['error' => 'Payment service temporarily unavailable'];
        }
    }
    
    return ['error' => 'Payment service is currently down'];
}

// Or resolve from container
$factory = app(CircuitBreakerFactory::class);
$breaker = $factory->make('api-service');

if (! $breaker->canAttempt()) {
    return cache()->remember('api-fallback-data', 3600, fn() => [...]);
}

// Check circuit state
if ($breaker->isOpen()) {
    // Circuit is open - requests are blocked
}

if ($breaker->isHalfOpen()) {
    // Circuit is testing recovery
}

// Get statistics
$stats = $breaker->getStats();
// [
//     'name' => 'payment-gateway',
//     'state' => 'open',
//     'failure_count' => 5,
//     'failure_threshold' => 5,
//     'recovery_timeout_seconds' => 300,
// ]

// Manually reset circuit
$breaker->reset();

[
    'defaults' => [
        'failure_threshold' => 5,          // Open circuit after 5 failures
        'window_seconds' => 60,            // Count failures within 60 seconds
        'recovery_timeout_seconds' => 300, // Try recovery after 5 minutes
        'half_open_max_attempts' => 3,     // Allow 3 tests before reopening
        'half_open_delay' => 1,            // Base delay, in seconds, between recovery attempts
    ],
    'notifiers' => [
        'email' => [
            'recipients' => null,      // Set email addresses for notifications
            'from_address' => null,    // Set sender email address
            'from_name' => 'Circuit Breaker',
        ],
    ],
]

use christopheraseidl\CircuitBreaker\Contracts\CacheContract;

class RedisCache implements CacheContract
{
    public function put(string $key, mixed $value, ?int $ttl = 1): bool
    {
        return $this->redis->setex($key, $ttl, serialize($value));
    }
    
    public function get(string $key, mixed $default = null): mixed
    {
        $value = $this->redis->get($key);
        return $value !== false ? unserialize($value) : $default;
    }
    
    // ... implement remaining methods
}
bash
php artisan vendor:publish --tag="circuit-breaker-config"
bash
php artisan vendor:publish --tag="circuit-breaker-views"