PHP code example of phparmory / rate

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

    

phparmory / rate example snippets


use Armory\Rate\{
    ActorFactory
};

$actorFactory = new ActorFactory();

$actor = $actorFactory->create('127.0.0.1');

use Armory\Rate\{
    EventFactory
};

$eventFactory = new EventFactory();

$event = $eventFactory->create('request.user.api', 1, $actor); // Cost of 1

use Armory\Rate\{
    RateLimitFactory
};

$rateLimitFactory = new RateLimitFactory();

$rateLimit = $rateLimitFactory->create(100, 60, 10); // 100 requests per minute (60 seconds) with a penalty of 10 seconds for hitting the rate limit

use Armory\Rate\{
    EventRepositoryFactory
};

$eventRepositoryFactory = new EventRepositoryFactory();

$repository = $eventRepositoryFactory->create(); // Defaults to FakeRepository

use Armory\Rate\{
    RateLimiterFactory
};

$rateLimiterFactory = new RateLimiterFactory();

$rateLimiter = $rateLimiterFactory->dynamic($event, $limit, $repository);

$rateLimiter->run();

use Armory\Rate\{
    EventFactory;
};

$eventFactory = new EventFactory;

$userApi = $eventFactory->create('user.api', 1, 0); // 1 credit
$postsApi = $eventFactory->create('posts.api', 2, 0); // 2 credits

use Armory\Rate\{
    EventFactory
};

$eventFactory = new EventFactory;

$userApi = $eventFactory->create('user.api', 1, 20); // Hitting the rate limit puts the actor in timeout for 20 seconds