倪惠英
php站内消息通知系统,Laravel的消息通知系统1.⽣成数据库
$ php artisan notifications:table
$ php artisan migrate
⽣成的表是notifications 数据结构是固定的
2.应⽤-⽣成话题回复通知类
$ php artisan make:notification TopicReplied
3. 触发通知
写在模型监控器⾥ --app/Obrvers/ReplyObrver.php
.
.
flit.
u App\Notifications\TopicReplied;
class ReplyObrver
{
public function created(Reply $reply)
{
$topic = $reply->topic;
$topic->increment('reply_count', 1);
// 通知作者话题被回复了
$topic->ur->notify(new TopicReplied($reply));
}
.
.
.
}
app/Models/Ur.php
.
.
.
u Auth;
class Ur extends Authenticatable
{
u Notifiable {
// Notifiable 的trait⾥⾯有notify⽅法,此处我们给它个别名
notify as protected laravelNotify;
}
网络安全风险评估public function notify($instance)
{
// 如果要通知的⼈是当前⽤户,就不必通知了!
if ($this->id == Auth::id()) {
return;
}
$this->increment('notification_count'); //字段加1
$this->laravelNotify($instance); // 发送通知
}
.
努组词组.
.
}
其实我们引⽤的是RoutesNotifications类的notify⽅法
public function notify($instance)
{
app(Dispatcher::class)->nd($this, $instance);
}
如果直接使⽤
Notification::nd($urs,new TopicReplied($reply));
框架内获取通知内容的trait⽂件
namespace Illuminate\Notifications;
trait HasDatabaNotifications
{
/**
* Get the entity's notifications.
*/
public function notifications()
{
return $this->morphMany(DatabaNotification::class, 'notifiable') ->orderBy('created_at', 'desc');
* Get the entity's read notifications.
*/
public function readNotifications()
{
return $this->notifications()
->whereNotNull('read_at');
}
/**
* Get the entity's unread notifications.
*/
public function unreadNotifications()
{
return $this->notifications()
-
>whereNull('read_at');
}
}
测试获取数据
$ur = Ur::find(1);
$test = $ur->notifications;
dd($test->toArray());
已读未读是有⼀个 read_at 字段
$ur->unreadNotifications; // 获取所有未读通知$ur->readNotifications; // 获取所有已读通知$ur->notifications; // 获取所有通知
图⽚.png
中国当代作家
4. 清除未读消息标⽰
.
.
.
class Ur extends Authenticatable
{
.
public function markAsRead()
{
$this->notification_count = 0;
$this->save();
$this->unreadNotifications->markAsRead();
}
}
樊锦诗简介使⽤
修改控制器的 index() ⽅法,新增清空未读提醒的状态:
app/Http/Controllers/NotificationsController.php
.
.
.
class NotificationsController extends Controller
{
.
.
.
public function index()
{
// 获取登录⽤户的所有通知
$notifications = Auth::ur()->notifications()->paginate(20);
// 标记为已读,未读数量清零
Auth::ur()->markAsRead();
return view('notifications.index', compact('notifications'));
}
}
这个handle⽅法就是我们要做的具体实现了,有个很⽅便的功能就是如果implements ShouldQueue这个接⼝的话就会异步队列执⾏,如果去掉的话就是同步执⾏。prais
注册的时候其实建议使⽤这种⽅式
namespace App\Providers;
u Laravel\Lumen\Providers\EventServiceProvider as ServiceProvider; class EventServiceProvider extends ServiceProvider
{
盛气凌人/**
* The event listener mappings for the application.
*
* @var array
*/
protected $listen = [
// ⽤户注册后的事件
'App\Events\Register' => [
// 发送⼴告邮件
'App\Listeners\SendAdMail',
// 发送短信
'App\Listeners\SendSms',
// 发送帮助信息
'App\Listeners\SendHelpInformation',
],
];
}
然后执⾏执⾏php artisan event:generater 直接会在相应的⽬录⽣成相应的这四个类