1. Go to this page and download the library: Download mahdi-mh/fallback-chain 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/ */
mahdi-mh / fallback-chain example snippets
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());
}
}
// 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.
});