美文网首页
扩展 Laravel 的消息通知系统(支持多语言和内容更改)

扩展 Laravel 的消息通知系统(支持多语言和内容更改)

作者: summerbluet | 来源:发表于2019-10-23 09:51 被阅读0次
    image

    文章转发自专业的Laravel开发者社区,原始链接:https://learnku.com/laravel/t/22473

    Laravel Notification 在 5.3 版本中被添加作为核心框架的扩展。它为我们提供了一种简单易懂,表现力强的 API 去发送通知,包括各种预置发送渠道还有 Laravel 社区提供的各种 自定义渠道

    其中一个重要的渠道是数据库通知,通知消息数据存储在数据库。下面是一个简单的例子,假设我们有一个 InvitationNotification 类,里面有 toArray 方法用来生成通知消息的标题和详情:

    <?php
    namespace App\Notifications;
    use App\Channels\FCMChannel;
    use App\Models\Invitation;
    use App\Models\User;
    use Illuminate\Contracts\Queue\ShouldQueue;
    use Illuminate\Notifications\Notification;
    class InvitationNotification extends Notification implements ShouldQueue
    {
        private $sender;
        private $invitation;
        public function __construct(User $sender, Invitation $invitation)
        {
            $this->sender = $sender;
            $this->invitation = $invitation;
        }
        public function via($notifiable)
        {
            return [FCMChannel::class, 'database'];
        }
        public function toArray($notifiable)
        {
            return [
                'title' => trans('notifications.new_invitation_title'),
                'details' => trans('notifications.new_invitation_details', [
                        'sender' => $this->sender->full_name,
                        'receiver' => $notifiable->full_name,
                        'relation' => $this->invitation->relation->name,
                        'invitation' => trans("mobile.invitation")
                    ]
                )
            ];
        }
    }
    

    瓶颈

    从前面的代码可以看出,Laravel 数据库通道会提前把 toArray 或者 toDatabase 方法生成的通知消息数据存储进数据库,这在某些项目中也许又用,但是仍然会有一些限制:

    • 如果有多种语言,用户可以随意选择切换语言,我们怎么这一条用英语显示 titledetail ,另一条用阿拉伯语?
    • 通知消息动态变化的,我们又该怎么做?比如,生日提醒「Today is John Doe's birthday」,第二天通知内容就应该变为「Yesterday was John Doe's birthday」诸如此类的场景。
    • 当一个用户收藏一篇帖子时,帖子的创建者就会收到通知「Jane doe liked your post」,而另一个用户收藏这篇帖子时,创建者会收到「Jon and Jane liked your post」。

    为了支持多种语言,我尝试过把键和参数的对应关系存储进数据库,读取通知数据时通过 trans 函数来转换 titledetails。但是问题是传输的参数也可能需要要再去翻译。

    还有就是,我们不能只是通过创建一条新的通知或者更新当前通知的内容来进行这些更改。

    解决办法

    当我为了找到最好的办法来解决这个问题而陷入僵局时,我有了另一个想法,于是我构建了这个扩展包。这个方案依赖于重写 * DatabaseChannel * 把通知数据存储为序列化通知对象,而不是存储键和值数组。

    <?php
    namespace App\Channels;
    use App\Models\CustomDatabaseNotification;
    use Illuminate\Notifications\Notification;
    class DatabaseChannel extends \Illuminate\Notifications\Channels\DatabaseChannel
    {
        /**
         * Send the given notification.
         *
         * @param mixed $notifiable
         * @param \Illuminate\Notifications\Notification $notification
         *
         * @return \Illuminate\Database\Eloquent\Model
         */
        public function send($notifiable, Notification $notification)
        {
            return $notifiable->routeNotificationFor('database', $notification)->create(
                $this->buildPayload($notifiable, $notification)
            );
        }
        /**
         * Get the data for the notification.
         *
         * @param mixed $notifiable
         * @param \Illuminate\Notifications\Notification $notification
         *
         * @throws \RuntimeException
         *
         * @return Notification
         */
        protected function getData($notifiable, Notification $notification)
        {
            return $notification;
        }
        /**
         * Build an array payload for the DatabaseNotification Model.
         *
         * @param mixed $notifiable
         * @param \Illuminate\Notifications\Notification $notification
         *
         * @return array
         */
        protected function buildPayload($notifiable, Notification $notification)
        {
            return [
                'id' => $notification->id,
                'type' => get_class($notification),
                'data' => ['data' => serialize($this->getData($notifiable, $notification))],
                'read_at' => null,
                'serialized' => true
            ];
        }
    }
    

    我还重写了 * DatabaseNotification * 模型,并添加了数据字段的访问器,以便在序列化数据后对数据进行反序列化,然后提取通知对象,最后调用 * toDatabase * 或 * toArray * 方法来获取最终输出。

    <?php
    namespace App\Models;
    class DatabaseNotification extends \Illuminate\Notifications\DatabaseNotification
    {
        public function getDataAttribute()
        {
            $data = $this->attributes['data'];
            if (isset($this->attributes['serialized']) && $this->attributes['serialized']) {
                $obj = unserialize($data['data']);
                if (method_exists($obj, 'toDatabase')) {
                    return $obj->toDatabase($this->notifiable);
                } else {
                    return $obj->toArray($this->notifiable);
                }
            } else {
                return $data;
            }
        }
    }
    

    优点

    通过使用这种方式,所有构建通知的代码都被移动到 * toDatabase * 或 * toArray * 方法来做处理。

    reactive-notification

    安装方法

    composer requires digitalcloud/reactive-notification

    发布和迁移

    php artisan vendor:publish provider="Digitalcloud\ReactiveNotification\ReactiveNotificationServiceProvider"
    php artisan migrate
    

    用法

    1. 更改模型中使用的特征
      从 *Illuminate\Notifications\Notifiable * 到 Digitalcloud\ReactiveNotification\Traits\Notifiable
    <?php
    namespace App;
    use Digitalcloud\ReactiveNotification\Traits\Notifiable;
    use Illuminate\Foundation\Auth\User as Authenticatable;
    class User extends Authenticatable
    {
        use Notifiable;
    }
    

    2. 从数据库更改传递的方法
    或者 *Illuminate\Notifications\Channels\DatabaseChannel * 到 Digitalcloud\ReactiveNotification\Channels\DatabaseChannel.

    <?php
    namespace App\Notifications;
    use Illuminate\Bus\Queueable;
    use Illuminate\Notifications\Notification;
    use Illuminate\Contracts\Queue\ShouldQueue;
    use Digitalcloud\ReactiveNotification\Channels\DatabaseChannel;
    class InvoicePaid extends Notification implements ShouldQueue
    {
        use Queueable;
        public function via($notifiable)
        {
            return [DatabaseChannel::class,'.../'];
        }
        
        public function toDatabase($notifiable){
            return [
              "title"=> trans("invoice_title"),
              "details"=> trans("invoice_details"),
            ];
        }
    }
    

    示例

    • 翻译:
    <?php
    $user->notify(new InvoicePaid($invoice));
    \App::setLocale("en");
    $result = $user->notifications()->first()->data; //result will be [ "title" => "Invoice title", "details" => "Invoice details" ]
    \App::setLocale("ar");
    $result = $user->notifications()->first()->data; //result will be [ "title" => "عنوان الفاتورة", "details" => "تفاصيل الفاتورة" ]
    
    • 内容动态地变化:
    <?php
    namespace App\Notifications;
    use App\Models\Member;
    use Carbon\Carbon;
    use Illuminate\Bus\Queueable;
    use Illuminate\Contracts\Queue\ShouldQueue;
    use Digitalcloud\ReactiveNotification\Channels\DatabaseChannel;
    class BirthDayNotification extends CustomNotification implements ShouldQueue
    {
        use  Queueable;
        private $member;
        public function __construct(Member $member)
        {
            $this->member = $member;
        }
        public function via()
        {
            return [DatabaseChannel::class];
        }
        public function toArray($notifiable)
        {
            $date = Carbon::parse($this->member->birthday)->format("m-d");
            if (today()->format("m-d") == $date) {
                $details = trans_choice('notifications.birth_day_today', $this->member->gender, ['name' => $this->member->name]);
            } elseif (today()->subDay()->format("m-d") == $date) {
                $details = trans_choice('notifications.birth_day_yesterday', $this->member->gender, ['name' => $this->member->name]);
            } else {
                $details = trans_choice('notifications.birth_day_old', $this->member->gender, ['name' => $this->member->name, "date" => $date]);
            }
            return [
                'title' => trans('notifications.birth_day_title'),
                'details' => $details
            ];
        }
    }
    
    $user->notify(new BirthDayNotification($member));
    $notification = $user->notifications()->first();
    

    如果一个成员的生日是今天,结果消息则为 “今天是 John 的生日,希望他过一个快乐生日!”

    如果成员的生日是昨天,最终消息体会改为 “John 昨天庆祝了他的生日”。

    Carbon::setTestNow(now()->addDay());
    

    最后要说的,如果成员的生日是具体日期,最终消息体会改为 “John 在12月31日庆祝了他的生日”。

    Carbon::setTestNow(now()->addMonths(3));
    

    希望你能喜欢使用这个包,并从列出的细节中获益。请继续关注其他有关高级 Laravel 消息通知的案例。

    相关文章

      网友评论

          本文标题:扩展 Laravel 的消息通知系统(支持多语言和内容更改)

          本文链接:https://www.haomeiwen.com/subject/hayhvctx.html