当数据库通知被创建时,将事件广播到 Pusher。
当数据库通知被创建时,将事件广播到 Pusher。
这与我先前提出的一个问题有关:Am I overcomplicating events/listeners/notifications?。
根据那个问题收到的反馈,我修改了我的方法,尝试做到以下几点:
- 触发一个数据库通知。
- 监听新的数据库通知的创建。
- 触发一个事件并广播给Pusher。
首先,我发送数据库通知:
Notification::send($this->requestedBy, new SendMonthlySummaryCreatedNotification($fileDownloadUrl, $fileName));
该通知类看起来像这样:
class SendMonthlySummaryCreatedNotification extends Notification implements ShouldQueue { use Queueable; public $fileDownloadUrl; public $fileName; /** * Create a new notification instance. * * @return void */ public function __construct($fileDownloadUrl, $fileName) { $this->fileDownloadUrl = $fileDownloadUrl; $this->fileName = $fileName; } /** * Get the notification's delivery channels. * * @param mixed $notifiable * @return array */ public function via($notifiable) { return ['database']; } /** * Get the array representation of the notification. * * @param mixed $notifiable * @return array */ public function toArray($notifiable) { return [ 'title' => 'Monthly Summary Complete', 'message' => "{$this->fileName} is ready. ", 'link' => $this->fileDownloadUrl, 'link_text' => 'Click here to download', 'show_toast' => true, 'user_id' => $notifiable->id ]; } }
我在文档中找到了这个示例,介绍了如何在模型中添加$dispatchesEvents
属性,我修改了它,应用到我创建的一个扩展DatabaseNotification
类的新模型上,我在这个SO问题上了解到这一点。
class Notification extends DatabaseNotification { use HasFactory; protected $dispatchesEvents = [ 'created' => NotificationCreatedEvent::class ]; public function users() { return $this->belongsTo(User::class, 'notifiable_id'); } }
理论上,以上代码应该在发送通知时触发一个事件,然后我有NotificationCreatedEvent
,我想用它来广播给Pusher:
class NotificationCreatedEvent implements ShouldBroadcast { use Dispatchable, InteractsWithSockets, SerializesModels; protected $notification; /** * Create a new event instance. * * @return void */ public function __construct(Notification $notification) { $this->notification = $notification; Log::debug($this->notification); } /** * Get the channels the event should broadcast on. * * @return \Illuminate\Broadcasting\Channel|array */ public function broadcastOn() { return new PrivateChannel('users.' . $this->notification->notifiable_id); } }
问题在于,一切都运行正常,直到NotificationCreatedEvent
。它似乎没有被触发。我不知道是否需要在新的Notification
模型中进行其他映射,或者它是否应该正常工作。
我的目标是添加一个数据库通知,然后每当发生通知时,将其发送到Pusher,以便我可以实时通知用户。这似乎应该能正常工作,但是我在Pusher中没有看到任何东西传递过来。