Resiliency, an implementation for resilient PHP 7 applications
Main principles
This library is compatible with PHP 7.2+.
Installation
composer require love-oss/resiliency
Use
You need to configure a system for the Circuit Breaker:
- the failures: define how much times we try to access the service;
- the timeout: define how long we wait before consider the service unreachable;
- the striped timeout: define how long we wait before consider the service unreachable, once we're in half open state;
- the threshold: define how long we wait before trying to access again the service;
- the (HTTP|HTTPS) client that will be used to reach the services;
- the fallback callback will be used if the distant service is unreachable when the Circuit Breaker is Open (means "is used").
You'd better return the same type of response expected from your distant call.
use Resiliency\MainCircuitBreaker;
use Resiliency\Systems\MainSystem;
use Resiliency\Storages\SimpleArray;
use Resiliency\Clients\SymfonyClient;
use Symfony\Component\HttpClient\HttpClient;
$client = new SymfonyClient(HttpClient::create());
$mainSystem = MainSystem::createFromArray([
'failures' => 2,
'timeout' => 0.1,
'stripped_timeout' => 0.2,
'threshold' => 10.0,
], $client);
$storage = new SimpleArray();
// Any PSR-14 Event Dispatcher implementation.
$dispatcher = new Symfony\Component\EventDispatcher\EventDispatcher;
$circuitBreaker = new MainCircuitBreaker(
$mainSystem,
$storage,
$dispatcher
);
/**
* @var Service $service
*/
$fallbackResponse = function ($service) {
return '{}';
};
$circuitBreaker->call(
'https://api.domain.com',
$fallbackResponse,
[
'query' => [
'_token' => '123456789',
]
]
);
Clients
Since v0.6, Resiliency library supports both Guzzle 6 and HttpClient Component from Symfony.
For the Guzzle implementation, the Client options are described in the HttpGuzzle documentation.
For the Symfony implementation, the Client options are described in the HttpClient Component documentation.
Monitoring
This library is shipped with a minimalist system to help you monitor your circuits.
$monitor = new SimpleMonitor();
// Collect information while listening
// to some circuit breaker events...
function listener(Event $event) {
$monitor->add($event);
};
// Retrieve a complete report for analysis or storage
$report = $monitor->getReport();
Tests
composer test
Code quality
This library have high quality standards:
composer cs-fix && composer phpstan && composer psalm
We also use PHPQA to check the Code quality during the CI management of the contributions:
composer phpqa