Laravel Notifynder 擴充實現 Laravel 應用的訊息通知功能

來源:互聯網
上載者:User

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) {
}

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.