繁体   English   中英

具有一个通知类的 Laravel 通知

[英]Laravel notification with one notification class

在我的网络应用程序中,我添加了通知功能。

有3个通知类。 应用通知/

  1. NotifWhenLiked.php
  2. NotifyWhenStoryCommented.php
  3. NotifyWhenAuthorFollowed.php

我想用一个 Notification 类来完成这些任务。 有没有最简单的方法来解决这个问题?

这是一类的代码

<?php

namespace App\Notifications;

use App\Http\Resources\Users;
use App\Model\User;
use App\Model\Story;
use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Notifications\Messages\MailMessage;
use Illuminate\Notifications\Notification;

class NotifyWhenLiked extends Notification implements ShouldQueue
{
    use Queueable;
    public $user;
    public $story;

    /**
     * Create a new notification instance.
     *
     * @return void
     */
    public function __construct(Story $story, User $user)
    {
        $this->user = $user;
        $this->story = $story;
    }

    /**
     * Get the notification's delivery channels.
     *
     * @param  mixed  $notifiable
     * @return array
     */
    public function via($notifiable)
    {
        return ['database','broadcast'];
    }

    /**
     * Get the mail representation of the notification.
     *
     * @param  mixed  $notifiable
     * @return \Illuminate\Notifications\Messages\MailMessage
     */
    public function toDatabase($notifiable)
    {
        return [

                'notification' => "<strong>".$this->user->name."</strong>". ' liked your story '. "<strong>".$this->story->title."</strong>",
                'Storylink' => '/story/'.$this->story->url_key,
                'Userlink' => '/a/'.$this->user->profile->username

    ];
    }

    /**
     * Get the array representation of the notification.
     *
     * @param  mixed  $notifiable
     * @return array
     */
    public function toArray($notifiable)
    {
        return [

                'notification' => $this->user->name. ' liked your story '. "<strong>".$this->story->title."</strong>",
                'username' => $this->user->profile->username,

        ];
    }
}

您可能会尝试将不同的通知类型存储到一个数组中,例如配置文件。

return [
   'when_liked' => [
      'notification_text' => '%s liked your story %s',
      'story_link' => '/story/%s'
   ],
   'when_commented' => [
      'notification_text' => '%s commented on your story %s',
      'story_link' => '/story/%s'
   ]
]

您可以创建一个通用的通知类,它负责处理通知内容。

$whenLikedNotification = new YourCustomNotificationClass('when_liked');
$whenLikedNotification->trigger();

在构造函数中,您可以处理配置内容。

我认为你可以使用一个事件来做到这一点

创建一个事件并调用与事件相关的所有侦听器( WhenLiked, WhenStoryCommented, WhenAuthorFollowed

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM