最近接手的项目需要实现站内消息功能,因为以前一直用laravel,本能就想到Laravel 的消息通知系统可以完美实现此功能。
但是由于系统的特性,当前项目使用lumen。正是由于lumen过于简洁,在项目运行
php artisan make:notification InvoicePaid
会提示
Command "make:notification" is not defined.
找到一篇英文文档完美解决此问题,大致翻译下:
Lumen本身不包含但是能够被安装的特性之一就是Laravel的消息通知功能。(其实很多的Laravel核心功能可以被安装到lumen中)。
laravel的消息通知功能非常有用,因为API在很多情况下可能希望生成通知,而Laravel通知服务是一种将邮件、短信息、Web套接字和其他类型通知结合在一起的简洁方法。
安装
下面开始安装步骤:
第一步:引入illuminate/notifications:
composer require illuminate/notifications
原作者还安装了illuminate/support,并没有确认两者之间的依赖关系。如果安装错误的话,很可能就是这个原因。
下一步:在bootstrap/app.php中注册service provider
$app->register(\Illuminate\Notifications\NotificationServiceProvider::class);
// optional: register the Facade
$app->withFacades(true, [
'Illuminate\Support\Facades\Notification' => 'Notification',
]);
之后就可以正常使用notification了
使用
lumen安装之后并不能像laravel的使用方法一样正常使notification
1.首先执行创建消息通知就会报错:
php artisan make:notification xxx
Command "make:notification" is not defined.
需要手动创建app/Notifications目录和notification文件
<?php
namespace App\Notifications;
use Illuminate\Bus\Queueable;
use Illuminate\Notifications\Notification;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Notifications\Messages\MailMessage;
class xxx extends Notification
{
use Queueable;
public function __construct()
{
}
public function via($notifiable)
{
return ['mail','database'];
}
public function toMail($notifiable)
{
$url = 'xxx.xxx.xx';
return (new MailMessage)
->subject('xxx')
->action('xxx', $url)
->line('xxx');
}
public function toDatabase($notifiable)
{
return[
'userinfo' => $notifiable,
];
}
public function toArray($notifiable)
{
return [
//
];
}
}
2.文件创建后调用时会报数据库notifications表不存在
而
php artisan notifications:table
命令一样不可用,这时需要找到建表文件
vendor/illuminate/notifications/Console/stubs/notifications.stub
复制其中的数据库迁移代码创建migration
数据库通知可用
3.发送通知邮件问题
这时tomail继续报错
这里需要注意mailer的安装和配置,可参考下文
https://blog.youkuaiyun.com/HQB421/article/details/80576397
mailer正常的情况下依然报错
Target [Illuminate\Contracts\Mail\Mailer] is not instantiable while building [Illuminate\Notifications\Channels\MailChannel].
最后查到原因,在bootstrap/app.php中加入
$app->alias('mailer', \Illuminate\Contracts\Mail\Mailer::class);
问题解决
4.用户实体没有email属性
邮件发送不报错了,但是用户没有收到通知邮件。因为用户数据中没有email字段,email地址用的其他命名。
解决办法
在用户的model中加入
public function routeNotificationForMail()
{
return $this->xxx;
}
问题解决
notification文档
https://learnku.com/docs/laravel/5.5/notifications/1322#listening-for-notifications
原文地址
https://stevethomas.com.au/php/using-laravel-notifications-in-lumen.html