PHPackages                             mahdi-mh/fallback-chain - 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. mahdi-mh/fallback-chain

ActiveLibrary

mahdi-mh/fallback-chain
=======================

A lightweight PHP package for building fallback chains with callable handlers and failure callbacks.

1.1.1(4mo ago)1329MITPHPPHP ^7.1 || ^8.0CI passing

Since Dec 14Pushed 4mo agoCompare

[ Source](https://github.com/mahdi-mh/fallback-chain)[ Packagist](https://packagist.org/packages/mahdi-mh/fallback-chain)[ RSS](/packages/mahdi-mh-fallback-chain/feed)WikiDiscussions main Synced 1mo ago

READMEChangelog (5)Dependencies (1)Versions (7)Used By (0)

Fallback Chain
==============

[](#fallback-chain)

[![Latest Version on Packagist](https://camo.githubusercontent.com/279abc63b65226aa0d5e3bcfe7525386ccfd6431fb2c51ebca2f5d1f33f977ca/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f762f6d616864692d6d682f66616c6c6261636b2d636861696e2e7376673f7374796c653d666c61742d737175617265)](https://packagist.org/packages/mahdi-mh/fallback-chain)[![Tests](https://github.com/mahdi-mh/fallback-chain/actions/workflows/tests.yml/badge.svg)](https://github.com/mahdi-mh/fallback-chain/actions/workflows/tests.yml)[![License](https://camo.githubusercontent.com/53e0a2fe61eb9c6676036bdc68bb54fe54c8634ad88cee65538be1fce9221172/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f6c2f6d616864692d6d682f66616c6c6261636b2d636861696e2e7376673f7374796c653d666c61742d737175617265)](https://packagist.org/packages/mahdi-mh/fallback-chain)

A lightweight PHP package for building fallback chains with callable handlers and failure callbacks.

Features
--------

[](#features)

- **Fluent Interface**: Build chains with a clean, readable syntax
- **Automatic Fallback**: Automatically continues to the next stage when one fails
- **Failure Callbacks**: Execute custom logic when a stage fails (logging, metrics, etc.)
- **Context Sharing**: Share data between all stages via a context object
- **Exception Collection**: Access all exceptions when the entire chain fails
- **PHP 7.1+ Compatible**: Works with PHP 7.1 through PHP 8.x

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

[](#installation)

Install the package via Composer:

```
composer require mahdi-mh/fallback-chain
```

Usage
-----

[](#usage)

### Basic Example

[](#basic-example)

```
use MahdiMh\FallbackChain\FallbackChain;
use MahdiMh\FallbackChain\Stage;
use MahdiMh\FallbackChain\AllStagesFailedException;

$context = [
    'to'   => '09121234567',
    'text' => 'Hello, this is a test message',
];

$chain = new FallbackChain($context);

$chain
    ->add(Stage::handler(function ($ctx) {
        return SmsProvider1::send($ctx['to'], $ctx['text']);
    })->onFailure(function (\Throwable $e, $ctx) {
        error_log('SMS Provider 1 failed: ' . $e->getMessage());
    }))

    ->add(Stage::handler(function ($ctx) {
        return SmsProvider2::send($ctx['to'], $ctx['text']);
    }))

    ->add(Stage::handler(function ($ctx) {
        return SmsProvider3::send($ctx['to'], $ctx['text']);
    })->onFailure(function (\Throwable $e, $ctx) {
        error_log('Provider 3 unavailable: ' . $e->getMessage());
    }));

try {
    $result = $chain->execute();
    echo "Message sent successfully: " . $result;
} catch (AllStagesFailedException $e) {
    echo "All providers failed.";

    // Access all exceptions that occurred
    foreach ($e->getExceptions() as $exception) {
        error_log($exception->getMessage());
    }
}
```

### How It Works

[](#how-it-works)

1. **Create a chain** with a shared context (any value - array, object, etc.)
2. **Add stages** using the fluent `add()` method
3. **Execute the chain** - it tries each stage in order:
    - If a stage succeeds (no exception), its result is returned immediately
    - If a stage fails (throws any `Throwable`), the optional `onFailure` callback runs
    - Execution continues to the next stage
4. **Handle total failure** - if all stages fail, `AllStagesFailedException` is thrown

### Use Cases

[](#use-cases)

- **Multiple SMS/Email Providers**: Try primary provider, fall back to secondary
- **Payment Gateways**: Attempt multiple payment processors
- **API Endpoints**: Try different API servers or mirrors
- **Cache Layers**: Check memory cache, then Redis, then database
- **File Storage**: Try local storage, then S3, then another cloud provider

### Creating Stages

[](#creating-stages)

```
// Stage with just a handler
$stage = Stage::handler(function ($context) {
    return doSomething($context);
});

// Stage with handler and failure callback
$stage = Stage::handler(function ($context) {
    return doSomething($context);
})->onFailure(function (\Throwable $e, $context) {
    // Log, send metrics, cleanup, etc.
});
```

### Accessing Failed Exceptions

[](#accessing-failed-exceptions)

When all stages fail, you can inspect all the exceptions:

```
try {
    $chain->execute();
} catch (AllStagesFailedException $e) {
    $exceptions = $e->getExceptions();

    foreach ($exceptions as $index => $exception) {
        echo "Stage {$index} failed: " . $exception->getMessage() . "\n";
    }
}
```

Testing
-------

[](#testing)

```
composer test
```

License
-------

[](#license)

The MIT License (MIT). Please see [License File](LICENSE) for more information.

###  Health Score

38

—

LowBetter than 85% of packages

Maintenance77

Regular maintenance activity

Popularity14

Limited adoption so far

Community6

Small or concentrated contributor base

Maturity44

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 ~5 days

Total

5

Last Release

126d ago

### Community

Maintainers

![](https://www.gravatar.com/avatar/7f7245b2105739a2483dd92b77fabef71a87258864dce11cc3a3d6139f1ca094?d=identicon)[mahdi-mh](/maintainers/mahdi-mh)

---

Top Contributors

[![mahdi-mh](https://avatars.githubusercontent.com/u/79706851?v=4)](https://github.com/mahdi-mh "mahdi-mh (18 commits)")

---

Tags

phphandlercallbackretryChainfallback

###  Code Quality

TestsPHPUnit

### Embed Badge

![Health badge](/badges/mahdi-mh-fallback-chain/health.svg)

```
[![Health](https://phpackages.com/badges/mahdi-mh-fallback-chain/health.svg)](https://phpackages.com/packages/mahdi-mh-fallback-chain)
```

###  Alternatives

[digitalstars/simplevk

Powerful PHP library/framework for VK API bots, supporting LongPoll &amp; Callback &amp; OAuth

883.9k3](/packages/digitalstars-simplevk)

PHPackages © 2026

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