PHP code example of 0xbliv / call-throttle

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

    

0xbliv / call-throttle example snippets


use ZeroxBliv\CallThrottle\Throttle;
use ZeroxBliv\CallThrottle\Store\RedisStore;

// Configure once → a frozen, reusable, id-bound throttler.
$throttle = Throttle::for('external-api')   // limiterId, shared across all workers
    ->allow(4)->per('second')               // 4 per second
    ->store(new RedisStore($redis))
    ->maxWait(10)                           // block at most 10s before throwing (optional)
    ->build();

// $response IS the callback's return value — usable exactly as a direct call.
$response = $throttle->run(fn () => Http::get('https://api.example.com/foo'));
$data = $response->json();

use ZeroxBliv\CallThrottle\{LimiterRegistry, RateLimit};
use ZeroxBliv\CallThrottle\Store\RedisStore;

// Once, at boot, in every worker (same store, same id):
$registry = new LimiterRegistry(new RedisStore($redis));
$registry->register('external-api', RateLimit::perMinute(100));

// Anywhere, in any process — no rate here, so it can't drift:
$response = $registry->limiter('external-api')->run(fn () => Http::get('https://api.example.com/foo'));
$registry->limiter('external-api')->run(fn () => Http::post('https://api.example.com/bar'));

$registry->limiter('external-api')->withMaxWait(30)->run(fn () => ...);   // this caller waits up to 30s
$registry->limiter('external-api')->withThrowOnLimit()->run(fn () => ...); // this caller fails fast

use ZeroxBliv\CallThrottle\Store\{RedisStore, FileStore, DatabaseStore};

new RedisStore($redis);                 // \Redis (phpredis) or \Predis\Client — atomic Lua, uses Redis clock
new FileStore('/var/run/throttle');     // flock; processes sharing a filesystem/host
new DatabaseStore($pdo);                // PDO; atomic transaction, row lock (FOR UPDATE) on MySQL/Postgres

// config/call-throttle.php
'limiters' => [
    'external-api' => '100/minute',
    'reports'      => ['rate' => '30/minute', 'max_wait' => 10],
    'webhooks'     => ['allow' => 5, 'per' => 'second', 'throw' => true],
],

use ZeroxBliv\CallThrottle\Laravel\Facades\CallThrottle;

$response = CallThrottle::limiter('external-api')
    ->run(fn () => Http::get('https://api.example.com/foo'));

// Per-caller wait policy (not the rate):
CallThrottle::limiter('external-api')->withMaxWait(30)->run(fn () => ...);

CallThrottle::for('one-off')->allow(4)->per('second')->run(fn () => ...);
CallThrottle::store('redis')->for('one-off')->allow(4)->per('second')->run(fn () => ...);