Skip to content

Instantly share code, notes, and snippets.

@houssenedao
Last active February 13, 2024 15:43
Show Gist options
  • Save houssenedao/ee1053e4c5def5420ca468f9807c6f22 to your computer and use it in GitHub Desktop.
Save houssenedao/ee1053e4c5def5420ca468f9807c6f22 to your computer and use it in GitHub Desktop.
Circuit breaker php
<?php
// The circuit breaker class
class CircuitBreaker
{
// The failure threshold
private $failureThreshold;
// The failure count
private $failureCount = 0;
// The state of the circuit
private $state = 'CLOSED';
// Constructor that sets the failure threshold
public function __construct($failureThreshold)
{
$this->failureThreshold = $failureThreshold;
}
// Method that checks if the circuit is open
public function isOpen()
{
return $this->state === 'OPEN';
}
// Method that checks if the circuit is closed
public function isClosed()
{
return $this->state === 'CLOSED';
}
// Method that increments the failure count and opens the circuit
// if the failure threshold has been reached
public function incrementFailureCount()
{
// Increment the failure count
$this->failureCount++;
// Check if the failure threshold has been reached
if ($this->failureCount >= $this->failureThreshold) {
// Set the state to open
$this->state = 'OPEN';
}
}
// Method that resets the failure count and closes the circuit
public function reset()
{
$this->failureCount = 0;
$this->state = 'CLOSED';
}
}
<?php
// Create the circuit breaker with a failure threshold of 3
$circuitBreaker = new CircuitBreaker(3);
// Check if the circuit is closed
if ($circuitBreaker->isClosed()) {
// Try to execute some operation
try {
executeOperation();
} catch (Exception $e) {
// Increment the failure count on error
$circuitBreaker->incrementFailureCount();
}
}
// Check if the circuit is open
if ($circuitBreaker->isOpen()) {
// Fall back to a different operation or handle the error
handleError();
}
// Reset the circuit breaker after a period of time
$circuitBreaker->reset();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment