【问题标题】:Laravel notification with one notification class带有一个通知类的 Laravel 通知
【发布时间】:2020-01-15 07:19:39
【问题描述】:

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

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

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

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

这是一个类的代码

<?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,

        ];
    }
}

【问题讨论】:

  • 如果所有类都执行类似的功能,那么只保留一个类并删除其他类。无论如何,您都必须更改手动发送这些通知的所有代码。

标签: php laravel laravel-5


【解决方案1】:

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

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();

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

【讨论】:

    【解决方案2】:

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

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

    【讨论】:

      猜你喜欢
      • 2021-07-19
      • 1970-01-01
      • 2018-04-02
      • 2020-01-20
      • 1970-01-01
      • 2017-10-11
      • 1970-01-01
      • 2018-01-13
      • 1970-01-01
      相关资源
      最近更新 更多