sndsgd/rate

PHP 的速率限制

0.1.2 2016-12-24 19:39 UTC

This package is not auto-updated.

Last update: 2024-09-14 19:25:37 UTC


README

Latest Version Software License Build Status Coverage Status Total Downloads

PHP 的速率限制。

要求

该项目不稳定,可能会从一次发布到下一次发布发生变化。

您需要 PHP >= 7.0 来使用此库,但建议使用最新稳定的 PHP 版本。

安装

使用 Composer 安装 sndsgd/rate

用法

注意:目前,此库仅包含速率限制工具。

# define the rate limits
$clientIp = $di->getClient()->getIp();
$limits = [
    new \sndsgd\rate\Limit("Search-PerSecond", $clientIp, 1, 3),
    new \sndsgd\rate\Limit("Search-PerHour", $clientIp, 600, 3600),
];

# create a limiter, and increment the hit counts for all limits
$redis = $di->getRedis();
$limiter = new \sndsgd\rate\limiter\RedisLimiter($redis, $limits);
$limiter->increment();

# copy the rate limit headers to the response
$response = $di->getResponse();
foreach ($limiter->getHeaders() as $header) {
    list($key, $value) = preg_split("/\:\s?/", $header, 2);
    $response->addHeader($key, $value);
}

# if the limit was exceeded, prevent futher execution
if ($limiter->isExceeded()) {
    throw new \sndsgd\http\exception\TooManyRequestsException();
}