PHP code example of syeedalireza / api-rate-limiter-bundle

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

    

syeedalireza / api-rate-limiter-bundle example snippets


use Syeedalireza\RateLimiterBundle\Attribute\RateLimit;

#[RateLimit(limit: 100, window: 3600)]
class ApiController extends AbstractController
{
    #[Route('/api/users')]
    #[RateLimit(limit: 10, window: 60, key: 'ip')]
    public function getUsers(): JsonResponse
    {
        // Max 10 requests per minute per IP
    }
}

use Syeedalireza\RateLimiterBundle\Service\RateLimiter;

public function __construct(
    private RateLimiter $rateLimiter
) {}

public function someAction(): Response
{
    $status = $this->rateLimiter->check('user:123', limit: 100, window: 3600);
    
    if (!$status->isAllowed()) {
        throw new TooManyRequestsHttpException(
            $status->getRetryAfter(),
            'Rate limit exceeded'
        );
    }
}

#[RateLimit(algorithm: 'token_bucket', limit: 100, window: 60)]

#[RateLimit(algorithm: 'sliding_window', limit: 100, window: 60)]

#[RateLimit(algorithm: 'fixed_window', limit: 100, window: 60)]

#[RateLimit(limit: 1000, window: 3600, cost: 10)]
public function heavyOperation(): Response
{
    // This request costs 10 tokens
}

#[RateLimit(limit: 10, window: 1)]     // 10 per second
#[RateLimit(limit: 100, window: 60)]   // 100 per minute
#[RateLimit(limit: 1000, window: 3600)] // 1000 per hour
public function api(): Response {}

$metrics = $this->rateLimiter->getMetrics('user:123');

echo $metrics->getRequestCount();
echo $metrics->getRemainingTokens();
echo $metrics->getResetTime();