PHP code example of securepoint / token-bucket

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

    

securepoint / token-bucket example snippets


use Securepoint\TokenBucket\Rate;
use Securepoint\TokenBucket\TokenBucket;
use Securepoint\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 Securepoint\TokenBucket\Rate;
use Securepoint\TokenBucket\TokenBucket;
use Securepoint\TokenBucket\BlockingConsumer;
use Securepoint\TokenBucket\Storage\FileStorage;

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

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

echo "API response";