Model

通知是由一个模型发出的,所以 Model 类中需要:

  1. use Notifiable;

定义 channel

一条通知可以通过短信发送,也可以通过邮件发送,指定 channel 就是指定该通知以什么样的方式发送出去。

  • 在 Notifications/Channels 目录下新建 XXXChannel 类
<?php

namespace App\Common\Notifications\Channels;

use JPush\Client as JPushClient;
use Illuminate\Notifications\Notification;

class JPushChannel
{
    protected $client;

    public function __construct(JPushClient $client)
    {
        $this->client = $client;
    }

    // $notifiable 是通知的发送者, 也就是上面说的 Model
    // $notification 就是一条通知, 消息需要通过 channel 发送
    public function send($notifiable, Notification $notification)
    {
        \Log::debug('此处发送到极光推送');
        $push = $notification->toJPush($notifiable, $this->client->push());
    }
}

注册 channel

在 AppServiceProvider 中:

public function register()
{
     $this->app->extend(ChannelManager::class, function ($manager) {
         $manager->extend('jpush', function ($app) { // jpush 是 channel 的名字
             return $app->make(JPushChannel::class); // 这里是刚才定义的 channel
         });
         return $manager;
     });
}

定义 Notification

php artisan make:notification XXX

  • 继承 Notification
  • via 方法是说明该通知将通过哪些 channel 发送出去
  • toXxxx 方法将在对应的 channel 中被调用, 比如通过 email 这个 channel 时将会调用 toEmail 方法
<?php

namespace App\Common\Notifications;

use Illuminate\Notifications\Notification;
use JPush\PushPayload;
use Log;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Bus\Queueable;

class FollowNotification extends Notification implements ShouldQueue
{   
    use Queueable; // 关联默认的队列

    public function via($notifiable)
    {
        return ['jpush'];
    }

    public function toJPush($notifialbe, PushPayload $payload) : PushPayload
    {
        Log::debug('followNotification');

        return $payload;
    }
}

发送通知

通过 Model 的 notify 方法, 发送该通知到指定的 channel

$user = UserModel::find(1);

$user->notify(new FollowNotification());