@@ -49,20 +49,53 @@ start using it in your application.
4949The Code
5050========
5151
52- You can find this file at **app/Filters/Throttle.php ** but the relevant method is reproduced here::
53-
54- public function before(RequestInterface $request)
55- {
56- $throttler = Services::throttler();
57-
58- // Restrict an IP address to no more
59- // than 1 request per second across the
60- // entire site.
61- if ($throttler->check($request->getIPAddress(), 60, MINUTE) === false)
62- {
63- return Services::response()->setStatusCode(429);
64- }
65- }
52+ You could make your own Throttler filter, at **app/Filters/Throttle.php **,
53+ along the lines of::
54+
55+ <?php namespace App\F ilters;
56+
57+ use CodeIgniter\F ilters\F ilterInterface;
58+ use CodeIgniter\H TTP\R equestInterface;
59+ use CodeIgniter\H TTP\R esponseInterface;
60+ use Config\S ervices;
61+
62+ class Throttle implements FilterInterface
63+ {
64+ /**
65+ * This is a demo implementation of using the Throttler class
66+ * to implement rate limiting for your application.
67+ *
68+ * @param RequestInterface|\C odeIgniter\H TTP\I ncomingRequest $request
69+ *
70+ * @return mixed
71+ */
72+ public function before(RequestInterface $request)
73+ {
74+ $throttler = Services::throttler();
75+
76+ // Restrict an IP address to no more
77+ // than 1 request per second across the
78+ // entire site.
79+ if ($throttler->check($request->getIPAddress(), 60, MINUTE) === false)
80+ {
81+ return Services::response()->setStatusCode(429);
82+ }
83+ }
84+
85+ //--------------------------------------------------------------------
86+
87+ /**
88+ * We don't have anything to do here.
89+ *
90+ * @param RequestInterface|\C odeIgniter\H TTP\I ncomingRequest $request
91+ * @param ResponseInterface|\C odeIgniter\H TTP\R esponse $response
92+ *
93+ * @return mixed
94+ */
95+ public function after(RequestInterface $request, ResponseInterface $response)
96+ {
97+ }
98+ }
6699
67100When run, this method first grabs an instance of the throttler. Next it uses the IP address as the bucket name,
68101and sets things to limit them to one request per second. If the throttler rejects the check, returning false,
@@ -79,8 +112,7 @@ this to incoming requests, you need to edit **/app/Config/Filters.php** and firs
79112filter::
80113
81114 public $aliases = [
82- 'csrf' => \App\Filters\CSRF::class,
83- 'toolbar' => \App\Filters\DebugToolbar::class,
115+ ...
84116 'throttle' => \App\Filters\Throttle::class
85117 ];
86118
@@ -92,9 +124,9 @@ Next, we assign it to all POST requests made on the site::
92124
93125And that's all there is to it. Now all POST requests made on the site will have be rate limited.
94126
95- ===============
127+ ***************
96128Class Reference
97- ===============
129+ ***************
98130
99131.. php :method :: check(string $key, int $capacity, int $seconds[, int $cost = 1])
100132
0 commit comments