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 [
// ...
'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
],
// ...
];
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');