PHP code example of yansongda / rate-limit-bundle

1. Go to this page and download the library: Download yansongda/rate-limit-bundle 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/ */

    

yansongda / rate-limit-bundle example snippets




namespace App\Controller;

use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Component\Routing\Annotation\Route;
use Yansongda\RateLimitBundle\Annotation\Throttle;

class HomeController extends AbstractController
{
    /**
     * 静态限流: 同一个 IP 访问 test 路由,60 秒内只能访问 2 次.
     *
     * @author yansongda <[email protected]>
     *
     * @Route("/test", name="test")
     * @Throttle(limit=2, period=60)
     * 
     * @return mixed
     */
    public function testAction()
    {
        return JsonResponse::create(['code' => 0]);
    }
}



namespace App\Controller;

use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Component\Routing\Annotation\Route;
use Yansongda\RateLimitBundle\Annotation\Throttle;

class HomeController extends AbstractController
{
    /**
     * 动态限流:具体的 limit 及 period 参数由 custom 返回.
     *
     * @author yansongda <[email protected]>
     *
     * @Route("/test", name="token")
     * @Throttle(limit=2, period=60, custom={"App\Throttles\CustomLimitPeriod", "token"})
     * 
     * @return mixed
     */
    public function tokenAction()
    {
        return JsonResponse::create(['code' => 0]);
    }
}



namespace App\Throttles;

use Symfony\Component\HttpFoundation\Request;

class CustomLimitPeriod
{
    /**
     * 自定义限流策略.
     *
     * @author yansongda <[email protected]>
     * @param Request $request 此参数回调时自动载入
     *
     * @return array
     */
    public function token(Request $request)
    {
        // 返回的数据中,第一个为 limit,第二个为 period,必须为 int 类型。如果 limit 返回 -1 则无限制
        return [20, 60];
    }
}