PHP code example of webrek / laravel-circuit-breaker

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

    

webrek / laravel-circuit-breaker example snippets


use Webrek\CircuitBreaker\Facades\CircuitBreaker;

$response = CircuitBreaker::for('payments')->call(
    fn () => Http::timeout(3)->post($url, $payload)->throw(),
    fallback: fn () => null,   // returned while the circuit is open
);

$rate = CircuitBreaker::for('fx-api')->call(
    fn () => $this->fetchLiveRate(),
    fallback: fn (\Throwable $e) => $this->lastKnownRate(),
);

use Webrek\CircuitBreaker\Exceptions\CircuitOpenException;

try {
    CircuitBreaker::for('payments')->call(fn () => $gateway->charge($order));
} catch (CircuitOpenException $e) {
    return back()->withErrors('Payments are temporarily unavailable.');
}

// config/circuit-breaker.php
'defaults' => [
    'ignore' => [
        Illuminate\Http\Client\RequestException::class, // only if you treat 4xx as a caller error
    ],
],

return [
    'cache' => [
        'store' => env('CIRCUIT_BREAKER_CACHE'),   // null = default; use Redis in production
        'prefix' => 'circuit-breaker',
        'ttl' => 86400,
    ],
    'defaults' => [
        'failure_threshold' => 5,    // consecutive failures that open the circuit
        'cooldown_seconds' => 30,    // open → half-open after this
        'success_threshold' => 1,    // trial successes needed to close
        'ignore' => [],              // exceptions that don't count as failures
    ],
    'circuits' => [
        'payments' => ['failure_threshold' => 3, 'cooldown_seconds' => 60],
    ],
];
bash
php artisan vendor:publish --tag=circuit-breaker-config
bash
php artisan circuit-breaker:reset payments