PHP code example of algoyounes / circuit-breaker

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

    

algoyounes / circuit-breaker example snippets


$circuit = $this->circuitManager->forService('service-name');


$circuit->onOpen(function (CircuitTransition $circuitTransition) { 
    // Your custom logic here
});

$circuit->onSuccess(function (CircuitResult $circuitResult, CircuitTransition $circuitTransition) {
    // Your custom logic here
});

// Params passed are optional

$circuit->run(function () {
    // Your service call here
});
// or
$circuit->run($this->serviceName->create(...));

> $circuit = CircuitBuilder::make('service-name')
> 

$this->circuitManager->run('service-name', function () {
    // Your service call here
});
// or
$this->circuitManager->run('service-name', $this->serviceName->create(...));

use AlgoYounes\CircuitBreaker\Middleware\GuzzleMiddleware;
use GuzzleHttp\Client;
use GuzzleHttp\HandlerStack;

$stack = HandlerStack::create();
$stack->push(GuzzleMiddleware::create());

$client = new Client([
    'handler' => $stack,
]);

$response = $client->get('https://api.example.com', [
    'headers' => [
        'X-Circuit-Key' => 'service-name',
    ],
]);

use Illuminate\Support\Facades\Http;

$response = Http::withCircuitBreaker('payment-service')
    ->get('https://api.payment.com/charge', [
        'amount' => 1000,
    ]);

$response = Http::withCircuitBreaker('shipping-service')
    ->withToken($apiToken)
    ->timeout(10)
    ->post('https://api.example.com/track', $payload);

use AlgoYounes\CircuitBreaker\Guzzle\Exceptions\RejectedException;

try {
    $response = Http::withCircuitBreaker('payment-service')
        ->get('https://api.example.com/charge');
} catch (RejectedException $e) {
    // Circuit is open — handle gracefully (e.g., return cached response, queue for retry)
}

'services' => [
    'payment-service' => [
        'failure_threshold' => 10,
        'cooldown_period'   => 120,
        'success_threshold' => 3,
    ],
],
bash
php artisan vendor:publish --provider="AlgoYounes\CircuitBreaker\Providers\CircuitBreakerServiceProvider" --tag="config"