PHP code example of gabrielanhaia / laravel-circuit-breaker

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

    

gabrielanhaia / laravel-circuit-breaker example snippets



// config/circuit_breaker.php

return [
    'default_driver' => env('CIRCUIT_BREAKER_DRIVER', 'redis'),

    'drivers' => [
        'redis' => [
            'connection' => env('CIRCUIT_BREAKER_REDIS_CONNECTION', 'default'),
            'prefix'     => 'cb:',
        ],
        'apcu' => [
            'prefix' => 'cb:',
        ],
        'memcached' => [
            'connection' => env('CIRCUIT_BREAKER_MEMCACHED_CONNECTION', 'memcached'),
            'prefix'     => 'cb:',
        ],
        'array' => [],
    ],
    // ...
];


// config/circuit_breaker.php

return [
    // ...
    'defaults' => [
        'failure_threshold'  => 5,     // Number of failures to open the circuit
        'success_threshold'  => 1,     // Successes in half-open to close the circuit
        'time_window'        => 20,    // Seconds in which failures are counted
        'open_timeout'       => 30,    // Seconds the circuit stays open before half-open
        'half_open_timeout'  => 20,    // Seconds the circuit stays half-open
        'exceptions_enabled' => false, // true = throw OpenCircuitException instead of returning false
    ],
    // ...
];


// config/circuit_breaker.php

return [
    // ...
    'services' => [
        'payment-api' => [
            'failure_threshold' => 3,   // More sensitive — fewer failures to trip
            'open_timeout'      => 60,  // Longer cooldown
        ],
        'email-service' => [
            'failure_threshold' => 10,  // More tolerant
        ],
    ],
];



namespace App\Services;

use GabrielAnhaia\LaravelCircuitBreaker\Facades\CircuitBreaker;
use Illuminate\Support\Facades\Http;

class PaymentService
{
    public function charge(array $data): mixed
    {
        if (!CircuitBreaker::canPass('payment-api')) {
            return $this->fallback();
        }

        try {
            $response = Http::timeout(5)->post('https://api.payment.example/charge', $data);

            CircuitBreaker::recordSuccess('payment-api');

            return $response->json();
        } catch (\Throwable $e) {
            CircuitBreaker::recordFailure('payment-api');

            return $this->fallback();
        }
    }

    private function fallback(): array
    {
        return ['status' => 'queued', 'message' => 'Payment will be retried shortly.'];
    }
}



namespace App\Services;

use GabrielAnhaia\LaravelCircuitBreaker\CircuitBreakerManager;
use Illuminate\Support\Facades\Http;

class PaymentService
{
    public function __construct(
        private readonly CircuitBreakerManager $circuitBreaker,
    ) {}

    public function charge(array $data): mixed
    {
        if (!$this->circuitBreaker->canPass('payment-api')) {
            return $this->fallback();
        }

        try {
            $response = Http::timeout(5)->post('https://api.payment.example/charge', $data);

            $this->circuitBreaker->recordSuccess('payment-api');

            return $response->json();
        } catch (\Throwable $e) {
            $this->circuitBreaker->recordFailure('payment-api');

            return $this->fallback();
        }
    }

    private function fallback(): array
    {
        return ['status' => 'queued'];
    }
}


// routes/api.php

use App\Http\Controllers\PaymentController;
use Illuminate\Support\Facades\Route;

Route::middleware('circuit-breaker:payment-api')
    ->post('/payments/charge', [PaymentController::class, 'charge']);

Route::middleware('circuit-breaker:email-service')
    ->post('/notifications/send', [NotificationController::class, 'send']);


// app/Providers/AppServiceProvider.php

namespace App\Providers;

use GabrielAnhaia\PhpCircuitBreaker\Event\CircuitOpenedEvent;
use GabrielAnhaia\PhpCircuitBreaker\Event\CircuitClosedEvent;
use GabrielAnhaia\PhpCircuitBreaker\Event\FailureRecordedEvent;
use GabrielAnhaia\PhpCircuitBreaker\Event\SuccessRecordedEvent;
use Illuminate\Support\Facades\Event;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\ServiceProvider;

class AppServiceProvider extends ServiceProvider
{
    public function boot(): void
    {
        Event::listen(CircuitOpenedEvent::class, function (CircuitOpenedEvent $event): void {
            Log::warning("Circuit OPENED for [{$event->getServiceName()}]");
        });

        Event::listen(CircuitClosedEvent::class, function (CircuitClosedEvent $event): void {
            Log::info("Circuit CLOSED for [{$event->getServiceName()}]");
        });
    }
}



use GabrielAnhaia\LaravelCircuitBreaker\Facades\CircuitBreaker;
use GabrielAnhaia\PhpCircuitBreaker\CircuitState;

// Block all traffic to a service (force OPEN)
CircuitBreaker::forceState('payment-api', CircuitState::OPEN);

// Block for 5 minutes, then automatically return to normal state logic
CircuitBreaker::forceState('payment-api', CircuitState::OPEN, ttl: 300);

// Remove the override
CircuitBreaker::clearOverride('payment-api');
bash
php artisan vendor:publish --tag=circuit-breaker-config