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表中建立一條新紀錄:
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) {
}