PHP code example of flix-tech / guzzle-circuit-breaker-middleware

1. Go to this page and download the library: Download flix-tech/guzzle-circuit-breaker-middleware 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/ */

    

flix-tech / guzzle-circuit-breaker-middleware example snippets




use Ejsmont\CircuitBreaker\Factory;
use FlixTech\CircuitBreakerMiddleware\Middleware;
use GuzzleHttp\Client;
use GuzzleHttp\Exception\RequestException;
use GuzzleHttp\HandlerStack;
use GuzzleHttp\Handler\CurlHandler;
use Psr\Http\Message\RequestInterface;

$circuitBreaker = Factory::getSingleApcInstance();

$serviceNameExtractor = function (RequestInterface $request, array $options) {
    if (\array_key_exists('my_custom_option_key', $options)) {
        return $options['my_custom_option_key'];
    }
    
    return null;
};

$exceptionMap = function ($rejectedValue) {
    if ($rejectedValue instanceof RequestException && $rejectedValue->getResponse()) {
        return 404 !== $rejectedValue->getResponse()->getStatusCode();
    }
    
    return true;
};

$middleware = new Middleware(
    $circuitBreaker,
    $serviceNameExtractor,
    $exceptionMap
);

$handlerStack = HandlerStack::create(new CurlHandler());
$handlerStack->push($middleware);

$client = new Client(['handler' => $handlerStack]);