PHPackages                             endisha/resilient-client - PHPackages - PHPackages  [Skip to content](#main-content)[PHPackages](/)[Directory](/)[Categories](/categories)[Trending](/trending)[Leaderboard](/leaderboard)[Changelog](/changelog)[Analyze](/analyze)[Collections](/collections)[Log in](/login)[Sign up](/register)

1. [Directory](/)
2. /
3. [Utility &amp; Helpers](/categories/utility)
4. /
5. endisha/resilient-client

ActiveLibrary[Utility &amp; Helpers](/categories/utility)

endisha/resilient-client
========================

Resilient Client is a PHP package designed to implement a circuit breaker pattern to enhance stability and prevent cascading failure requests

1.0.1(2y ago)29MITPHPPHP ^8.1

Since Aug 29Pushed 2y ago1 watchersCompare

[ Source](https://github.com/endisha/resilient-client)[ Packagist](https://packagist.org/packages/endisha/resilient-client)[ RSS](/packages/endisha-resilient-client/feed)WikiDiscussions main Synced 1mo ago

READMEChangelog (2)Dependencies (4)Versions (3)Used By (0)

Resilient Client
================

[](#resilient-client)

[![Latest Stable Version](https://camo.githubusercontent.com/665bd87684885950cc0911e3bfccbebd8fdc0ddd23be2dc4aa63fe15982101bb/687474703a2f2f706f7365722e707567782e6f72672f656e64697368612f726573696c69656e742d636c69656e742f76)](https://packagist.org/packages/endisha/resilient-client)[![Total Downloads](https://camo.githubusercontent.com/3cb2cf5a452254cc28a6663a8bd848d3a1e33dc9a32aa2d8a0374758faf5a9d5/687474703a2f2f706f7365722e707567782e6f72672f656e64697368612f726573696c69656e742d636c69656e742f646f776e6c6f616473)](https://packagist.org/packages/endisha/resilient-client)

Resilient Client is a PHP package designed to implement a circuit breaker pattern to enhance stability and prevent cascading failure requests.

### What is circuit breaker pattern?

[](#what-is-circuit-breaker-pattern)

The Circuit Breaker is a design pattern used in software development. It is used to detect and prevent cascading request failures due to slow network connectivity, timeouts, unavailability, or unexpected system difficulties.

Requirements
------------

[](#requirements)

- PHP ^8.1 or higher

Installation
------------

[](#installation)

You can install the package via Composer by running the following command:

```
composer require endisha/resilient-client

```

Usage
-----

[](#usage)

To use the package in your project, include the Composer autoload file:

```
require_once __DIR__ . '/vendor/autoload.php';
```

Implementing the circuit breaker pattern:

```
use ResilientClient\CircuitBreaker;
use ResilientClient\CircuitBreaker\Adapters\FileStorageAdapter;

$adapter = new FileStorageAdapter;
$adapter->setPath(__DIR__ . '/storage/');

$circuitBreaker = new CircuitBreaker($adapter);
// The maximum number of consecutive failures that can occur before the circuit breaker trips and enters a [failed] state
$circuitBreaker->setFailureThreshold(3);
// The duration that the circuit breaker waits in an [open] state before allowing test requests to determine if the service has recovered (In seconds)
$circuitBreaker->setResetTimeout(300);
```

The `CircuitBreaker` constructor also allows setting a custom key as the second parameter; the default value is `default`

```
$circuitBreaker = new CircuitBreaker($adapter, 'github-cb');
```

Adapters
--------

[](#adapters)

The package supports two types of adapters, each serving as a method of state storage for the circuit breaker pattern:

- File Storage Adapter: Stores states within files.
- PDO Database Adapter: Uses PDO to store states in a database.

#### File Storage Adapter

[](#file-storage-adapter)

To use the File Storage Adapter and save circuit states to files use `FileStorageAdapter` and follow these steps:

```
use ResilientClient\CircuitBreaker\Adapters\FileStorageAdapter;
$adapter = new FileStorageAdapter;
$adapter->setPath('path/to/storage');
```

#### Database (PDO) Adapter

[](#database-pdo-adapter)

To use the Database (PDO) Adapter and work with PDO to save states in the `circuit_breaker` table, you need to create the custom table first:

```
CREATE TABLE `circuit_breaker` (
  `id` bigint(20) unsigned NOT NULL AUTO_INCREMENT,
  `key` varchar(40) COLLATE utf8_unicode_ci NOT NULL DEFAULT '',
  `state` varchar(40) COLLATE utf8_unicode_ci NOT NULL DEFAULT '',
  `failure_count` int(11) NOT NULL,
  `last_failure_time` int(11) DEFAULT NULL,
  `updated_at` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
```

Create an instance of `PDODatabaseAdapter` class

```
use ResilientClient\CircuitBreaker\Adapters\PDODatabaseAdapter;
use PDO;

// PDO connection
$pdo = new PDO("mysql:host=localhost;dbname=name", 'user', 'pass');
// Use PDODatabaseAdapter
$adapter = new PDODatabaseAdapter($pdo);
$adapter->setTable('circuit_breaker'); //table: circuit_breaker
```

How it Works
------------

[](#how-it-works)

- To check if the circuit is open (not available), use:

```
$circuit->isNotAvaiable();
```

- To mark a request as successful:

```
$circuit->success();
```

- To mark a request as failed:

```
$circuit->failure();
```

### Example

[](#example)

```
use ResilientClient\CircuitBreaker\Adapters\FileStorageAdapter;
use ResilientClient\CircuitBreaker\CircuitBreaker;
use ResilientClient\CircuitBreaker\Exceptions\CircuitBreakerException;

$adapter = new FileStorageAdapter;
$adapter->setPath(__DIR__ . '/storage/');

$circuitBreaker = new CircuitBreaker($adapter);
$circuitBreaker->setFailureThreshold(3);
$circuitBreaker->setResetTimeout(300);

try {

    if ($circuitBreaker->isNotAvailable()) {
        throw new CircuitBreakerException('Service is unreachable');
    }

    // Send request
    // ....
    $successRequest = true;
    // ....

    if ($successRequest) {
        $circuitBreaker->success();
    } else {
        $circuitBreaker->failure();
    }
} catch (\CircuitBreakerException $e) {
    echo $e->getMessage();
}
```

Guzzle Integration
------------------

[](#guzzle-integration)

The package supports integration with Guzzle through the `CircuitBreakerGuzzleMiddleware` middleware. This middleware is automatically implemented when `ConnectException` exceptions are thrown due to problems connecting to remote servers or establishing connections. To implement it, follow these steps:

```
use GuzzleHttp\Client;
use GuzzleHttp\Handler\CurlHandler;
use GuzzleHttp\HandlerStack;
use ResilientClient\CircuitBreaker\Middleware\CircuitBreakerGuzzleMiddleware;

$stack = HandlerStack::create(new CurlHandler());
$middleware = new CircuitBreakerGuzzleMiddleware($circuitBreaker);
$stack->push($middleware);

$args['handler'] = $stack;
$client = new Client($args);
// etc..
```

Additionally, you can specify certain HTTP status codes as failure requests. For example, you might want to treat errors like 301 (Moved Permanently) and 302 (Found) as failure responses:

```
use GuzzleHttp\Client;
use GuzzleHttp\Handler\CurlHandler;
use GuzzleHttp\HandlerStack;
use ResilientClient\CircuitBreaker\Middleware\CircuitBreakerGuzzleMiddleware;

$stack = HandlerStack::create(new CurlHandler());
$middleware = new CircuitBreakerGuzzleMiddleware($circuitBreaker);
$middleware->setAsFailureRequestCodes(301, 302);
$stack->push($middleware);

$args['handler'] = $stack;
$client = new Client($args);
// etc..
```

#### Handling Exceptions

[](#handling-exceptions)

When the circuit breaker is in an open state, it throws the `ResilientClient\CircuitBreaker\Exceptions\CircuitBreakerException` exception class. This exception serves as a signal that the circuit is currently open and requests to the service are not allowed. You can catch this exception to implement custom handling logic in your application when the circuit is open.

#### Example usage:

[](#example-usage)

```
use GuzzleHttp\Client;
use GuzzleHttp\Handler\CurlHandler;
use GuzzleHttp\HandlerStack;
use ResilientClient\CircuitBreaker\Adapters\FileStorageAdapter;
use ResilientClient\CircuitBreaker\CircuitBreaker;
use ResilientClient\CircuitBreaker\Middleware\CircuitBreakerGuzzleMiddleware;

$adapter = new FileStorageAdapter;
$adapter->setPath(__DIR__ . '/storage/');

$circuitBreaker = new CircuitBreaker($adapter);
$circuitBreaker->setFailureThreshold(3);
$circuitBreaker->setResetTimeout(300);

$stack = HandlerStack::create(new CurlHandler());

$middleware = new CircuitBreakerGuzzleMiddleware($circuitBreaker);
$middleware->setAsFailureRequestCodes(301, 302);
$stack->push($middleware);

$args['handler'] = $stack;
$client = new Client($args);
// etc..
```

Tests
-----

[](#tests)

```
composer test

```

License
-------

[](#license)

The Resilient Client package is open-source software licensed under the [MIT](https://opensource.org/licenses/MIT) License.

###  Health Score

24

—

LowBetter than 32% of packages

Maintenance20

Infrequent updates — may be unmaintained

Popularity7

Limited adoption so far

Community7

Small or concentrated contributor base

Maturity53

Maturing project, gaining track record

 Bus Factor1

Top contributor holds 100% of commits — single point of failure

How is this calculated?**Maintenance (25%)** — Last commit recency, latest release date, and issue-to-star ratio. Uses a 2-year decay window.

**Popularity (30%)** — Total and monthly downloads, GitHub stars, and forks. Logarithmic scaling prevents top-heavy scores.

**Community (15%)** — Contributors, dependents, forks, watchers, and maintainers. Measures real ecosystem engagement.

**Maturity (30%)** — Project age, version count, PHP version support, and release stability.

###  Release Activity

Cadence

Every ~7 days

Total

2

Last Release

978d ago

### Community

Maintainers

![](https://www.gravatar.com/avatar/3a407eae966764db8707b080a72d787dc2a4b2f759ce1fb673edf0860ad59c32?d=identicon)[endisha](/maintainers/endisha)

---

Top Contributors

[![endisha](https://avatars.githubusercontent.com/u/22410829?v=4)](https://github.com/endisha "endisha (2 commits)")

---

Tags

circuit-breakerpackagepatternphpphpclientpackagedesignpatterncircuitbreakerresilient

###  Code Quality

TestsPHPUnit

Static AnalysisPHPStan

Type Coverage Yes

### Embed Badge

![Health badge](/badges/endisha-resilient-client/health.svg)

```
[![Health](https://phpackages.com/badges/endisha-resilient-client/health.svg)](https://phpackages.com/packages/endisha-resilient-client)
```

###  Alternatives

[wujunze/money-wrapper

MoneyPHP Wrapper

113.8k](/packages/wujunze-money-wrapper)

PHPackages © 2026

[Directory](/)[Categories](/categories)[Trending](/trending)[Changelog](/changelog)[Analyze](/analyze)
