syropian/laravel-notification-channel-throttling

v1.0.1 2024-03-07 03:08 UTC

This package is auto-updated.

Last update: 2024-09-08 17:55:49 UTC


README

Laravel Notification Channel Throttling

🚦 Laravel Notification Channel Throttling

按渠道限制Laravel通知

Latest Version on Packagist GitHub Tests Action Status GitHub Code Style Action Status Total Downloads

简介

当通过多个渠道(例如电子邮件和短信)发送通知时,您可能希望限制通过特定渠道发送的通知数量。例如,您可以限制每天向用户发送的短信通知数量为1条,电子邮件为5条。此包允许您直接在通知类中轻松配置此功能。

安装

您可以通过composer安装此包

composer require syropian/laravel-notification-channel-throttling

用法

  1. 确保您想限制的通知实现了 Syropian\LaravelNotificationChannelThrottling\Contracts\ThrottlesChannels
  2. 实现 throttleChannels 方法。此方法应返回一个包含要限制的渠道及其配置的数组。要排除某个渠道,要么从数组中省略该渠道,要么将其值设置为 false
use Illuminate\Notifications\Notification;
use Syropian\LaravelNotificationChannelThrottling\Contracts\ThrottlesChannels;

class ExampleNotification extends Notification implements ThrottlesChannels {
    // ...

    public function throttleChannels(object $notifiable, array $channels): array
    {
        /**
         * Throttle the mail channel, so that only one
         * email notification is sent every 15 minutes
         */
        return [
            'mail' => [
                'maxAttempts' => 1,
                'decaySeconds' => 900,
            ],
            'database' => false,
        ];
    }
}

速率限制器的范围

默认情况下,用于限制的通知和渠道的速率限制器实例自动范围到通知和渠道。如果您想进一步限制速率限制器,可以向渠道配置传递一个 key

public function __construct(public Post $post) {}

public function throttleChannels(object $notifiable, array $channels): array
{
    return [
        'mail' => [
            'key' => $notifiable->id . ':' . $this->post->id,
            'maxAttempts' => 1,
            'decaySeconds' => 900,
        ],
        'database' => false,
    ];
}

在这个例子中,我们正在限制邮件渠道,并将其范围限定为用户和帖子的特定组合。

测试

composer test

致谢

许可证

MIT许可证(MIT)。请参阅许可证文件以获取更多信息。