cellard / throttle
此包已被弃用且不再维护。未建议替代包。
Laravel Throttle 服务可以限制任何事件,而不仅仅是请求
1.0.4
2020-08-04 11:07 UTC
Requires
- php: >=7.0
- laravel/framework: >=6.0
This package is auto-updated.
Last update: 2023-11-23 14:34:33 UTC
README
Laravel 内置的限流功能允许限制对路由的访问速率。但其他进程怎么办,例如发送短信呢?
例如,你可能需要限制用户从你的服务中接收短信的数量。或者你可能需要限制用户在一定时间内可以发表评论的数量。
此服务可以限制你需要的任何事件
try { throttle('sms') ->subject('+70001234567') ->try(); // Your code to send SMS here } catch (\Cellard\Throttle\ThrottlingException $exception) { // No, You Don't }
安装
composer require Cellard/throttle
在 config/app.php
文件中注册服务提供者。
'providers' => [ /** * Third Party Service Providers... */ Cellard\Throttle\ThrottleServiceProvider::class ],
将包配置文件和迁移发布到你的应用程序。在终端中运行以下命令。
php artisan vendor:publish --provider="Cellard\Throttle\ThrottleServiceProvider"
并且也要运行迁移。
php artisan migrate
设置
设置你的限流服务。
class ThrottleSms extends Cellard\Throttle\ThrottleService { public function rules() { return [ '1:60', // one sms per minute '3:300', // 3 sms per 5 minutes '5:86400', // maximum 5 sms every day ]; } }
完全相同,但是带有辅助工具。
class ThrottleSms extends Cellard\Throttle\ThrottleService { public function rules() { return [ $this->everyMinute(), $this->everyFiveMinutes(3), $this->daily(5) ]; } }
然后在 config/throttle.php
中注册你的服务。
return [ 'events' => [ 'sms' => ThrottleSms::class ] ];
错误信息
默认错误信息看起来像 Next :event after :interval
Next sms after 23 hours 32 minutes 13 seconds
你可以定义自定义错误信息。
class ThrottleSms extends Cellard\Throttle\ThrottleService { public function rules() { return [ '1:60' => 'You may send only one SMS per minute', '3:300' => 'You may send no more than three SMS in five minutes' ]; } }
占位符
- limit — 事件数量(在规则中定义)
- seconds — 秒数(在规则中定义)
- event — 服务名称(在配置文件中定义)
- interval -
CarbonInterval
对象(到下一次允许的击打剩余时间)
使用
$throttle = Throttle::event('sms')->subject('+70001234567'); if ($throttle->allow()) { // Your code to send SMS here // Do not forget to register an event $throttle->hit(); } else { // Show error message $throttle->error(); // Show the time, next sms is allowed $throttle->next(); }
或者以 try-catch 风格
try { Throttle::event('sms') ->subject('+70001234567') ->try(); // Your code to send SMS here } catch (\Cellard\Throttle\ThrottlingException $exception) { // Show error message $exception->getMessage(); // Show the time, next sms is allowed $exception->getNext(); }
你也可以使用辅助函数。
throttle('sms') ->subject('+70001234567') ->try();
什么是 subject
?
Subject
是一个范围。
你可以不使用主题来检查可用性。
Throttle::event('sms')->try();
这意味着服务将检查限制,而不参考确切的电话号码。
主题表示服务将按电话号码检查限制。
Throttle::event('sms')->subject('+70001234567')->try();
在你离开房间之前检查你的房间
Throttle 服务在其表中存储记录,你可能想要清除它。
php artisan throttle:clean
将删除过时的记录。
你可以安排它每天或每周运行一次...