1. Go to this page and download the library: Download muffin/throttle 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/ */
public function middleware(MiddlewareQueue $middlewareQueue): MiddlewareQueue
{
// Various other middlewares for error handling, routing etc. added here.
$throttleMiddleware = new \Muffin\Throttle\Middleware\ThrottleMiddleware([
// Data used to generate response with HTTP code 429 when limit is exceeded.
'response' => [
'body' => 'Rate limit exceeded',
],
// Time period as number of seconds
'period' => 60,
// Number of requests allowed within the above time period
'limit' => 100,
// Client identifier
'identifier' => function ($request) {
if (!empty($request->getHeaderLine('Authorization'))) {
return str_replace('Bearer ', '', $request->getHeaderLine('Authorization'));
}
return $request->clientIp();
}
]);
$middlewareQueue->add($throttleMiddleware);
return $middlewareQueue;
}
\Cake\Event\EventManager::instance()->on(
\Muffin\Throttle\Middleware\ThrottleMiddleware::EVENT_BEFORE_THROTTLE,
function ($event, $request) {
if (/* check for something here, most likely using $request */) {
$event->stopPropagation();
}
}
);
\Cake\Event\EventManager::instance()->on(
\Muffin\Throttle\Middleware\ThrottleMiddleware::EVENT_GET_THROTTLE_INFO,
function ($event, $request, \Muffin\Throttle\ValueObject\ThrottleInfo $throttle) {
// Set a different period for POST request.
if ($request->is('POST')) {
// This will change the cache key from default "{identifer}" to "{identifer}.post".
$throttle->appendToKey('post');
$throttle->setPeriod(30);
}
// Modify limit for logged in user
$identity = $request->getAttribute('identity');
if ($identity) {
$throttle->appendToKey($identity->get('role'));
$throttle->setLimit(200);
}
}
);