PHP code example of villermen / token-bucket

1. Go to this page and download the library: Download villermen/token-bucket 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/ */

    

villermen / token-bucket example snippets


use JouwWeb\TokenBucket\Rate;
use JouwWeb\TokenBucket\TokenBucket;
use JouwWeb\TokenBucket\storage\FileStorage;

$storage = new FileStorage(__DIR__ . "/api.bucket");
$rate = new Rate(10, Rate::SECOND);
$bucket = new TokenBucket(10, $rate, $storage);
$bucket->bootstrap(10);

if (!$bucket->consume(1, $seconds)) {
    http_response_code(429);
    header(sprintf("Retry-After: %d", floor($seconds)));
    exit();
}

echo "API response";

use JouwWeb\TokenBucket\BlockingConsumer;
/** @var \JouwWeb\TokenBucket\TokenBucket $bucket */

$consumer = new BlockingConsumer($bucket);

// This will block until one token is available.
$consumer->consume(1);

echo "API response";