PHP code example of rtheunissen / guzzle-rate-limiter

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

    

rtheunissen / guzzle-rate-limiter example snippets


use Concat\Http\Middleware\RateLimiter;

$handlerStack->push(new RateLimiter($rateLimitProvider));



use Psr\Http\Message\ResponseInterface;
use Psr\Http\Message\RequestInterface;
use Concat\Http\Middleware\RateLimitProvider;

/**
 * An object which manages rate data for a rate limiter, which uses the data to
 * determine wait duration. Keeps track of:
 *
 *  - Time at which the last request was made
 *  - The allowed interval between the last and next request
 */
class Provider implements RateLimitProvider
{
    /**
     * Returns when the last request was made.
     *
     * @return float|null When the last request was made.
     */
    public function getLastRequestTime()
    {
        // This is just an example, it's up to you to store the time of the
        // most recent request, whether it's in a database or cache driver.
        return Cache::get('last_request_time');
    }

    /**
     * Used to set the current time as the last request time to be queried when
     * the next request is attempted.
     */
    public function setLastRequestTime()
    {
        // This is just an example, it's up to you to store the time of the
        // most recent request, whether it's in a database or cache driver.
        return Cache::forever('last_request_time', microtime(true));
    }

    /**
     * Returns what is considered the time when a given request is being made.
     *
     * @param RequestInterface $request The request being made.
     *
     * @return float Time when the given request is being made.
     */
    public function getRequestTime(RequestInterface $request)
    {
        return microtime(true);
    }

    /**
     * Returns the minimum amount of time that is ow much time is remaining in our window
        // divided by the number of requests we can still make. This is the 
        // value we need to store to determine if a future request should be 
        // delayed or not.
        $allowance = (float) $seconds / $requests;
    
        // This is just an example, it's up to you to store the request 
        // allowance, whether it's in a database or cache driver.
        Cache::forever('request_allowance', $allowance);
    }
}