evoluted/php-ratelimiter

PHP 的无框架速率限制器

1.3.1 2016-08-23 16:25 UTC

This package is auto-updated.

Last update: 2024-09-25 13:54:17 UTC


README

PHP 的一个独立、灵活且高度可扩展的速率限制器。

SensioLabsInsight Scrutinizer Code Quality Code Coverage Code Climate Build Status Latest Stable Version License

安装

使用 Composer

最佳安装方式是通过 Packagist 包管理器,在你的项目 composer.json 的 require 部分包含 sunspikes/php-ratelimiter

    "require": {
        "sunspikes/php-ratelimiter":  "dev-master"
    }

不使用 Composer

你也可以从 [Github] 下载它(https://github.com/sunspikes/php-ratelimiter),但不会提供自动加载器,因此你需要使用自己的 PSR-4 兼容自动加载器进行注册。

使用方法

概述

// 1. Make a rate limiter with limit 3 attempts in 10 minutes
$cacheAdapter = new DesarrollaCacheAdapter((new DesarrollaCacheFactory())->make());
$ratelimiter = new RateLimiter(new ThrottlerFactory(), new HydratorFactory(), $cacheAdapter, 3, 600);

// 2. Get a throttler for path /login 
$loginThrottler = $ratelimiter->get('/login');

// 3. Register a hit
$loginThrottler->hit()

// 4. Check if it reached the limit
if ($loginThrottler->check()) {
    // access permitted
} else {
    // access denied
}

// Or combine the steps 3 & 4
if ($loginThrottler->access()) {
    // access permitted
} else {
    // access denied
}

// To get the number of hits
print $loginThrottler->count(); // or count($throttler)

配置

默认情况下,PHP Ratelimiter 使用 desarolla2 缓存适配器,在 config/config.php 中提供的示例配置。

你可以在 config.php 中配置驱动程序,例如,要使用 memcache,将驱动程序更改为 'memcache'

return [
    'default_ttl' => 3600,
    'driver'      => 'memcache',
    'memcache' => [
        //....
    ],
];

扩展

PHP Ratelimiter 非常可扩展,你可以通过实现 Sunspikes\Ratelimit\Cache\Adapter\CacheAdapterInterface 来创建自定义适配器。

例如,要使用 Doctrine 缓存适配器

class DoctrineCacheAdapter implements CacheAdapterInterface
{
    public function __construct($cache)
    {
        $this->cache = $cache;
    }
    
    // Implement the methods
}

// Build adapter using APC cache driver
$adapter = new DoctrineCacheAdapter(new \Doctrine\Common\Cache\ApcCache());

你也可以通过实现 Sunspikes\Ratelimit\Throttle\Hydrator\DataHydratorInterface 来创建自定义 hydrator

例如,要使用 Symfony 请求对象而不是自定义 URL 进行速率限制

class RequestHydrator implements DataHydratorInterface
{
    public function hydrate($data, $limit, $ttl)
    {
        // Make the key string
        $key = $data->getClientIp() . $data->getPathInfo();

        return new Data($key, $limit, $ttl);
    }
}

// Hydrate the request to Data object
$hydrator = new RequestHydrator();

然后装饰或扩展 HydratorFactory 以识别你的数据

use Hydrator\FactoryInterface;

class MyHydratorFactory implements FactoryInterface
{
    private $defaultFactory;

    public function __construct(FactoryInterface $defaultFactory)
    {
        $this->defaultFactory = $defaultFactory;
    }

    public function make($data)
    {
        if ($data instanceof Request) {
            return new RequestHydrator();
        }

        return $this->defaultFactory->make($data);
    }
}

作者

Krishnaprasad MG [@sunspikes]

贡献

请随时发送 pull request。

许可证

这是一个开源软件,受 MIT 许可证 许可。