ivfuture / laravel-event-notification
本包提供了一种简单的方式,将实时通知与Laravel 6、Redis和socket.io集成。
Requires
- php: ^7.2
- predis/predis: ^1.1
Requires (Dev)
- phpunit/phpunit: ^7.0
This package is auto-updated.
Last update: 2024-09-15 23:42:56 UTC
README
本包提供了一种简单的方式,将通知与Laravel 6、Redis和socket.io集成。安装后,用户将能够接收实时通知。
以下是一些示例
// at the top of your class use NotificationTrait; //Controller's constructor public function __construct() { //subscribe to all the notification channels from database $this->subscribeToNotificationChannels(); // ... } //sending a notification $notification_channel = NotificationChannel::where('label', 'post-liked')->first(); if (!isset($notification_channel)) { return response()->json(['success' => false]); } $this->sendNotification($p_sender_id, $p_receiver_id, $p_notifiable_type, $p_notifiable_id, $notification_channel->id, $p_title, $p_description);
安装
您可以使用composer安装此包:
composer require ivfuture/laravel-event-notification
要注册包,您需要在您的config/app.php文件中添加服务提供者
'providers' => [ // ... Ivfuture\EventNotification\NotificationServiceProvider::class, ];
现在,您应该使用以下命令发布迁移:
php artisan vendor:publish --provider="Ivfuture\EventNotification\NotificationServiceProvider"
迁移发布后,您可以通过运行迁移来创建表格:
php artisan migrate
接下来,我们必须安装npm包
npm install express socket.io ioredis redis --save
设置
首先,您必须编辑您的.env文件,以告诉Laravel使用正确的BROADCAST_DRIVER。
BROADCAST_DRIVER=redis
如果您使用的是较旧的Laravel版本,您可能可以跳过下一步。您需要编辑您的config/database.php文件,并注释掉添加redis前缀的行
'redis' => [ 'options' => [ 'cluster' => env('REDIS_CLUSTER', 'redis'), //'prefix' => env('REDIS_PREFIX', Str::slug(env('APP_NAME', 'laravel'), '_').'_database_'), ], // ... ],
启动服务器
现在,您只需启动服务器即可。
node vendor/ivfuture/laravel-event-notification/src/socket.js redis-server --port 3001
使用方法
安装包并完成所有设置后,是时候在您的项目中集成通知了。
首先,不要忘记在文件顶部导入特质。
use NotificationTrait;
订阅通知频道
在您的控制器构造函数中,您必须订阅频道。您可以通过使用NotificationTrait的subscribeToNotificationChannels()函数来实现。它将在notification_channel表中查找频道,并自动订阅它们。
public function __construct() { $this->subscribeToNotificationChannels(); // ... }
发送通知
还有一个方便的函数用于发送通知
$notification_channel = NotificationChannel::where('label', 'post-liked')->first(); $this->sendNotification($p_sender_id, $p_receiver_id, $p_notifiable_type, $p_notifiable_id, $notification_channel->id, $p_title, $p_description);
这将把通知保存到数据库中,并发送包含所有数据的event。
从数据库获取通知
您可以从数据库中获取通知
Notification::latest()->where('receiver_id', auth()->user()->id )->get()->groupByDate();
这将根据时间分类提供通知,如:今天、本周、上周或更早。
在视图中接收通知
要接收实时通知,您必须遵循以下3个步骤
1 - 导入socket.io库
<script src="https://cdnjs.cloudflare.com/ajax/libs/socket.io/2.1.1/socket.io.dev.js"></script>
2 - 创建一个Socket对象。
var socket = io('{{ env("APP_URL") }}:3000');
注意:默认情况下,服务器将监听端口3000。您可以通过编辑.env文件中的PORT值来更改它。
3 - 监听发送通知的频道。
socket.on("post-liked", function (data) { // ... });
注意:如果您有多个频道,您必须监听所有频道。
示例
socket.on("post-liked", function (data) { // ... }); socket.on("post-commented", function (data) { // ... });
最后,不要忘记检查用户是否是通知的接收者。
if (data.receiver_id == "{{auth()->user()->id}}") { // ... }