Add rate limits to your controllers / actions easily through annotations
Add rate limits to your controllers / actions easily through annotations
This bundle provides enables the #[RateLimit()] attribute which allows you to limit the number of connections to actions.
This is mostly useful in APIs.
The bundle is prepared to work by default in cooperation with the FOSOAuthServerBundle. It contains a listener that adds the OAuth token to the cache-key. However, you can create your own key generator to allow custom rate limiting based on the request. See Create a custom key generator below.
This bundle is partially inspired by a GitHub gist from Ruud Kamphuis.
Installation takes just few easy steps:
If you're not yet familiar with Composer see http://getcomposer.org. Tell composer to download the bundle by running the command:
composer require noxlogic/ratelimit-bundleIf you are using symfony/flex you can skip this step, the bundle will be enabled automatically,
otherwise you need to enable the bundle by adding it to the bundles.php file of your project.
['all' => true],
// ..
];If you want to use Redis as your storage engine, you might want to install SncRedisBundle:
If you want to use Memcache, you might want to install LswMemcacheBundle
If you want to use Doctrine cache as your storage engine, you might want to install DoctrineCacheBundle:
Referer to their documentations for more details. You can change your storage engine with the storage_engine configuration parameter. See Configuration reference.
If you wish to enable the bundle only in production environment (so you can test without worrying about limit in your development environments), you can use the enabled configuration setting to enable/disable the bundle completely. It's enabled by default:
# config_dev.yml
noxlogic_rate_limit:
enabled: falseThis is the default bundle configuration:
…To enable rate limiting, you only need to add the attribute to the specified action
generateKey();
$event->addToKey($key);
// $event->setKey($key); // to overwrite key completely
}
}Make sure to generate a key based on what is rate limited in your controllers.
And example of a IP-based key generator can be:
getRequest();
$event->addToKey($request->getClientIp());
}
}Instead of returning a Response object when a rate limit has exceeded, it's also possible to throw an exception. This
allows you to easily handle the rate limit on another level, for instance by capturing the kernel.exception event.
If you want to run the tests use:
./vendor/bin/simple-phpunitNo open issues yet, or sync has not completed.