PHP code example of bayfrontmedia / leaky-bucket

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

    

bayfrontmedia / leaky-bucket example snippets


use Bayfront\LeakyBucket\Adapters\Flysystem;

$adapter = new Flysystem($filesystem, '/root_path');

use Bayfront\LeakyBucket\Adapters\Local;

$adapter = new Local('/root_path');

use Bayfront\LeakyBucket\Adapters\PDO;

$adapter = new PDO($dbh, 'table_to_use');

try {

    $adapter->up();

} catch (AdapterException $e) {
    die($e->getMessage());
}

use Bayfront\LeakyBucket\Adapters\Redis;

$redis = new Redis();

try {
    $redis->pconnect('10.0.0.1', 6379, 2, 'cache');
} catch (RedisException $e) {
    $redis->connect('10.0.0.1', 6379, 2);
}

$redis->auth([
    'USERNAME',
    'PASSWORD'
]);

$adapter = new \Bayfront\LeakyBucket\Adapters\Redis($redis, 'bucket:prefix:', 3600);

use Bayfront\LeakyBucket\AdapterException;
use Bayfront\LeakyBucket\BucketException;
use Bayfront\LeakyBucket\Bucket;

// Create/retrieve a bucket with a given ID

try {

    $bucket = new Bucket('bucket_id', $adapter, [
        'capacity' => 10, // Total drop capacity
        'leak' => 10 // Number of drops to leak per minute
    ]);

} catch (AdapterException | BucketException $e) {
    die($e->getMessage());
}

// Work with the bucket

$bucket->leak();

if ($bucket->hasCapacity()) {

    try {

        $bucket->fill()->save();

    } catch (AdapterException $e) {
        die($e->getMessage());
    }

}

if ($bucket->exists()) {
    // Do something
}

try {

    $bucket->save();

} catch (AdapterException $e) {
    die($e->getMessage());
}

$contents = $bucket->get();

$bucket->reset();

try {

    $bucket->delete();

} catch (AdapterException $e) {
    die($e->getMessage());
}

if ($bucket->isFull()) {
    // Do something
}

echo $bucket->getCapacity();

echo $bucket->getCapacityUsed();

echo $bucket->getCapacityRemaining();

if ($bucket->hasCapacity(5)) {
    // Do something
}

echo $bucket->getLeakPerSecond();

echo $bucket->getSecondsPerDrop();

echo $bucket->getSecondsPerDrop();

echo $bucket->getSecondsUntilEmpty();

$bucket->touch();

echo $bucket->getLastTime();

try {
    
    $bucket->fill();
    
} catch (BucketException $e) {
    die($e->getMessage());
}

$bucket->leak();

$bucket->spill(5);

$bucket->overflow();

$bucket->dump();

if ($bucket->hasData('client_id')) {
    // Do something
}

$bucket->setData('client_id', 5);

$client_id = $bucket->getData('client_id');

$bucket->forgetData('client_id');