本书未发布
消息通知
通知是 Laravel 工具箱中的强大工具,因为它们支持将通知发送到一系列不同的服务,包括邮件,SMS,Slack或将其存储在数据库中以显示在用户的个人资料页面上。
创建通知
要开始在包中使用通知,请首先在包的 src/
目录中创建一个 Notifications
目录。
在此示例中,添加一个 PostWasPublishedNotification.php
,以通知 Post
的作者其提交已被批准。
<?php
namespace JohnDoe\BlogPackage\Notifications;
use Illuminate\Notifications\Messages\MailMessage;
use Illuminate\Notifications\Notification;
use JohnDoe\BlogPackage\Models\Post;
class PostWasPublishedNotification extends Notification
{
public $post;
public function __construct(Post $post)
{
$this->post = $post;
}
/**
* 获取通知的传递渠道。
*
* @param mixed $notifiable
* @return array
*/
public function via($notifiable)
{
return ['mail'];
}
/**
* 获取通知的邮件表示形式。
*
* @param mixed $notifiable
* @return \Illuminate\Notifications\Messages\MailMessage
*/
public function toMail($notifiable)
{
return (new MailMessage)
->line("Your post '{$this->post->title}' was accepted")
->action('Notification Action', url("/posts/{$this->post->id}"))
->line('Thank you for using our application!');
}
/**
* 获取通知的数组表示形式。
*
* @param mixed $notifiable
* @return array
*/
public function toArray($notifiable)
{
return [
//
];
}
}
测试通知
在本测试中:
- 通过
fake()
辅助函数将Notification
门面替换成模拟的。 - 判断在调用
notify()
方法之前尚未发送任何通知。 - 通过
$ user-> notify()
(需要使用Notifiable
trait )来通知User
模型。 - 确认通知已发送并包含正确的
Post
模型。
<?php
namespace JohnDoe\BlogPackage\Tests\Unit;
use Illuminate\Support\Facades\Notification;
use JohnDoe\BlogPackage\Models\Post;
use JohnDoe\BlogPackage\Notifications\PostWasPublishedNotification;
use JohnDoe\BlogPackage\Tests\TestCase;
use JohnDoe\BlogPackage\Tests\User;
class NotifyPostWasPublishedTest extends TestCase
{
/** @test */
public function it_can_notify_a_user_that_a_post_was_published()
{
Notification::fake();
$post = factory(Post::class)->create();
// 用户模型具有 'Notifiable' trait
$user = factory(User::class)->create();
Notification::assertNothingSent();
$user->notify(new PostWasPublishedNotification($post));
Notification::assertSentTo(
$user,
PostWasPublishedNotification::class,
function ($notification) use ($post) {
return $notification->post->id === $post->id;
}
);
}
}
通过测试后,您可以安全地在包中使用此通知。
自定义通知渠道
此外,您可以将通知通道配置为依赖于包的配置文件,以允许用户指定他们要使用的通知通道。
public function via($notifiable)
{
return config('blogpackage.notifications.channels');
}
...然后将 notifications.channels
子条目添加到配置文件中(请参见第7章)
本译文仅用于学习和交流目的,转载请务必注明文章译者、出处、和本文链接
我们的翻译工作遵照 CC 协议,如果我们的工作有侵犯到您的权益,请及时联系我们。
推荐文章: