PHP code example of spatie / guzzle-rate-limiter-middleware

1. Go to this page and download the library: Download spatie/guzzle-rate-limiter-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/ */

    

spatie / guzzle-rate-limiter-middleware example snippets


use GuzzleHttp\Client;
use GuzzleHttp\HandlerStack;
use Spatie\GuzzleRateLimiterMiddleware\RateLimiterMiddleware;

$stack = HandlerStack::create();
$stack->push(RateLimiterMiddleware::perSecond(3));

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

RateLimiterMiddleware::perSecond(3); // Max. 3 requests per second

RateLimiterMiddleware::perMinute(5); // Max. 5 requests per minute

use MyApp\RateLimiterStore;
use Spatie\GuzzleRateLimiterMiddleware\RateLimit;

RateLimiterMiddleware::perSecond(3, new RateLimiterStore());



namespace MyApp;

use Spatie\GuzzleRateLimiterMiddleware\Store;
use Illuminate\Support\Facades\Cache;

class RateLimiterStore implements Store
{
    public function get(): array
    {
        return Cache::get('rate-limiter', []);
    }

    public function push(int $timestamp, int $limit)
    {
        Cache::put('rate-limiter', array_merge($this->get(), [$timestamp]));
    }
}