1、簡介
Notifynder 以簡單的方式提供了強大的消息通知管理功能:其提供的完整API可用於對消息通知的各種處理,比如存儲、檢索以及組織處理成百上千條通知的代碼庫。有了Notifynder,你可以在幾分鐘內在你的Laravel項目中“啓用”消息通知功能。
目前支持的數據庫包括MySQL、Postgres和SQLite。
2、安裝
使用Composer安裝該擴展:
composer require fenos/notifynder
然後到config/app.php
中註冊服務提供者:
Fenos\Notifynder\NotifynderServiceProvider::class,
以及門面:
'Notifynder' => Fenos\Notifynder\Facades\Notifynder::class,
發佈該擴展包的配置文件到config
目錄:
php artisan vendor:publish --provider="Fenos\Notifynder\NotifynderServiceProvider"
最後運行數據庫遷移生成相應數據表:
php artisan migrate
3、快速上手
創建分類
在開始使用Notifynder之前,我們需要簡單瞭解“分類”這一術語在Notifynder中的職責,分類是消息通知的主體,通過唯一的名稱來區分,並且擁有對應的通知文本,每個通知都要綁定到一個分類上,以便於管理和維護。
首先我們使用Notifynder提供的Artisan命令來創建一個分類 :
php artisan notifynder:create:category "user.following" "{from.username} started to follow you"
這會在數據庫notification_categories
表中創建一條新紀錄:
功能實現
接下來確定要被通知的模型,通常我們選擇User
模型,這個被選擇的模型類要使用 Notifable
Trait:
use Fenos\Notifynder\Notifable; class User extends Model{ use Notifable; }
這樣我們的模型實體就可以處理消息通知了:
$user = User::find(1); $user->getNotifications($limit = null, $paginate = null, $order = 'desc'); $user->getNotificationsNotRead($limit = null, $paginate = null, $order = 'desc'); $user->getLastNotification(); $user->countNotificationsNotRead($category = null); $user->readAllNotifications();
注:如果你不想使用
Notifable
Trait,也可以直接使用Notifynder
門面上的對應方法。
4、發送通知
發送通知非常簡單:
$from_user_id = 1; $to_user_id = 2; Notifynder::category('user.following') ->from($from_user_id) ->to($to_user_id) ->url('http://laravelacademy.org/notifications') ->send();
發送通知後我們來檢索通知:
$userNotified = User::find($to_user_id); dd($userNotified->getNotificationsNotRead());
還可以一次發送多個通知,這裏我們給多個用戶發送通知:
// It send a notification to all the users try { $this->notifynder->loop($users, function(NotifynderBuilder $builder, $user) { $builder->category('sayhello') ->from(1) ->to($user->id) ->url('http://localhost') ->extra(compact('period_day')); })->send(); } catch (EntityNotIterableException $e) { } catch (IterableIsEmptyException $e) { }