跳至正文

通知 ​

简介 ​

客户支付发票后,你可能需要给客户发送邮件、短信,并将付款信息发到所属团队的 Slack 频道。通过通知,你只需描述一次事件,再为每个渠道构建相应消息,Laravel 会将消息发送给指定的每位用户或每个团队。

Laravel 支持通过邮件、短信、Slack 以及 Discord 等扩展包自定义渠道发送通知。电子邮件使用邮件模块,短信使用短信模块,并沿用各自的配置和队列,请先配置好需要使用的渠道。

通知应简短并提供必要信息。如果要发送订单收据等带有专属布局和附件的单封邮件,请直接发送邮件对象。

编写通知 ​

每个通知由保存消息所需数据的结构体和带 #[notification] 标记的 impl 块组成。为支持的每个渠道分别定义 mail、sms 或 slack 方法,通常将通知放在 src/notifications.rs 这样的模块中。

假设应用有 Invoice 模型和 InvoicePaidEmail 邮件对象。下面的通知会在用户支付发票后提醒用户:

rust
use laravel::mail::Mailable;
use laravel::notification;

use crate::mail::InvoicePaidEmail;

pub struct InvoicePaid {
    pub invoice: Invoice,
}

#[notification]
impl InvoicePaid {
    fn mail(&self, user: &User) -> impl Mailable {
        InvoicePaidEmail { name: user.name.clone(), invoice_id: self.invoice.id }
    }

    fn sms(&self, _user: &User) -> String {
        format!("Invoice #{} is paid. Thanks!", self.invoice.id)
    }
}

每个方法的第二个参数是消息的接收者,这里为 &User。同一个 impl 块内的所有方法都接收相同类型的接收者。如果还需要通知团队,可以再写一个 #[notification] 实现,让各方法接收 &Team,参见 Slack 示例。

渠道方法是同步的,应在发送前加载所需的关联模型和数据。Laravel 会在分发通知的处理器或任务内调用这些方法,因此可以直接访问路由 URL、配置和上下文值。如果某个渠道方法可能失败(例如生成路由 URL),可以返回 laravel::Result,任何错误都会在所有消息投递之前中止发送。

通知与邮件对象一样拥有其数据的所有权,便于模拟工具在测试中保存它。如果发送后还需使用某个值,请将它克隆进通知,例如 InvoicePaid { invoice: invoice.clone() }。

邮件消息 ​

mail 返回发给一个接收者的邮件。返回值可以是通过派生宏定义的邮件对象、自行构建消息的邮件对象,或 Message。InvoicePaidEmail 是派生的邮件对象,它用 name 和 invoice_id 渲染 resources/views/mail/invoice-paid-email.html:

rust
use laravel::mail::Mailable;

#[derive(Mailable)]
#[mail(subject = "Invoice #{invoice_id} is paid")]
pub struct InvoicePaidEmail {
    pub name: String,
    pub invoice_id: i64,
}

Laravel 自动将接收者的电子邮件地址设为收件人,因此邮件对象无需指定 to。有关视图、主题和附件的更多用法,见邮件指南。

短信消息 ​

sms 可以用 String 或 &str 返回短信文本,通过 SMS_FROM 号码发送。如需使用其他发送号码,请返回 sms::Message:

rust
use laravel::sms;

fn sms(&self, _user: &User) -> sms::Message {
    sms::Message::new(format!("Invoice #{} is paid.", self.invoice.id)).from("+15555550199")
}

Slack 消息 ​

slack 返回 slack::Message,可包含分区和按钮等内容块。Slack 消息通常发到团队频道。假设应用有 Team 模型,其中包含 slack_channel_id 列:

rust
use laravel::notification;
use laravel::prelude::*;
use laravel::slack::{Button, Message, Section};

#[notification]
impl InvoicePaid {
    fn slack(&self, _team: &Team) -> laravel::Result<Message> {
        let url = route!(invoices::show, &self.invoice)?;
        let amount = format!("${:.2}", self.invoice.total as f64 / 100.0);

        Ok(Message::new(format!("Invoice #{} is paid", self.invoice.id))
            .section(Section::new("Invoice paid.").field("Amount", amount))
            .actions([Button::link("View invoice", url)]))
    }
}

消息会发往团队的 Slack 路由。有关 Slack 应用设置与按钮点击处理,见 Slack 指南。

通知接收者 ​

接收者是 User 或 Team 等可以接收通知的类型。为它支持的各渠道实现 ReceivesMail、ReceivesSms 或 ReceivesSlack,以提供邮件地址、电话号码或 Slack 路由。假设用户表中有允许为空的 phone 列:

rust
use laravel::mail::Address;
use laravel::notification::{ReceivesMail, ReceivesSlack, ReceivesSms};
use laravel::slack::Route;
use laravel::sms::PhoneNumber;

impl ReceivesMail for User {
    fn mail_address(&self) -> Option<Address> {
        Some(Address::new(&self.email).with_name(&self.name))
    }
}

impl ReceivesSms for User {
    fn sms_number(&self) -> Option<PhoneNumber> {
        self.phone.as_deref().map(PhoneNumber::new)
    }
}

impl ReceivesSlack for Team {
    fn slack_route(&self) -> Option<Route> {
        self.slack_channel_id.as_deref().map(Route::channel)
    }
}

当某个方法返回 None 时,就会跳过该接收者的相应渠道,整个发送过程仍正常进行。注册时没有提供手机号码的用户仍然可以收到邮件。

接收者必须为通知构建消息所用的每个渠道提供相应实现。向没有实现 ReceivesSms 的类型发送 InvoicePaid 会导致编译错误。

发送通知 ​

使用 notification::to 指定接收者,然后调用 queue 或 send。大多数处理器应将通知交给队列,以便 HTTP 响应无需等候外部服务。这个处理器对发票扣款,然后通知客户:

rust
use laravel::notification;
use laravel::prelude::*;

use crate::models::Invoice;
use crate::notifications::InvoicePaid;

pub async fn pay(Params(id): Params<i64>) -> laravel::Result<Redirect> {
    let invoice = Invoice::query()
        .with(Invoice::user)
        .find_or_fail(id)
        .await?;

    // 为发票扣款……

    notification::to(&invoice.user)
        .queue(InvoicePaid { invoice: invoice.clone() })
        .await?;

    Ok(Redirect::back())
}

send 立即投递,并等待各服务提供商接受消息。to 接受一个接收者的引用、接收者切片或 Vec、包含引用的 Vec、Authenticated<User>,或 &invoice.user、&team.members 等已加载的关联。以下示例同时通知多个团队:

rust
let teams = Team::all().await?;

notification::to(&teams).send(WeeklySummary { report }).await?;

同一个通知为多种接收者类型实现 #[notification] 时,Rust 无法从 &Vec<T>、&Authenticated<T> 或已加载的关联包装类型推断目标类型。此时请传入切片,或先对包装值解引用:

rust
let teams = Team::all().await?;

notification::to(teams.as_slice()).send(InvoicePaid { invoice }).await?;

将通知加入队列 ​

queue 通过队列工作进程发送消息,并在提供商失败时独立重试各消息。因此,请在将通知入队之前启动工作进程。等待 queue 前,可以延迟投递并选择消息任务所用的队列:

rust
use laravel::time::ToSpan;

notification::to(&user)
    .queue(InvoicePaid { invoice })
    .delay(5.minutes())
    .on_queue("notifications")
    .await?;

queue 为每个接收者和渠道组合分发一个任务,与队列邮件和队列短信相同。向三位用户经两个渠道发送会产生六个任务,某条短信失败时只重试该短信,不会重复发送邮件。

省略 on_connection 和 on_queue 时,邮件任务使用 MAIL_QUEUE_CONNECTION 和 MAIL_QUEUE,短信任务使用 SMS_QUEUE_CONNECTION 和 SMS_QUEUE,Slack 与扩展包渠道的任务则使用默认连接和队列。

如果在数据库事务内将通知入队,Laravel 会等待事务提交后再分发任务。事务回滚时,队列通知会被丢弃,用户不会收到关于未保存变更的通知。

为每位接收者选择渠道 ​

默认情况下,通知通过 #[notification] 块中定义的所有渠道投递。你可能希望用户能单独订阅或退出某个渠道,或根据通知数据选择渠道。在通知中加入 channels 方法即可按接收者控制投递。例如,用户表中有一个可以通过设置页面配置的 sms_alerts 列:

rust
use laravel::notification;
use laravel::notification::{Mail, Selected, Sms};

#[notification]
impl InvoicePaid {
    // `mail` 和 `sms` 与之前相同……

    fn channels(&self, user: &User, channels: &mut Selected<Self, User>) {
        channels.add(Mail);

        if user.sms_alerts && self.invoice.total >= 10_000 {
            channels.add(Sms);
        }
    }
}

Laravel 会在构建任何消息之前,为每位接收者执行一次 channels。它既不能等待异步操作,也不能返回错误,因此无法在其中查询数据库。发送前请将所需数据加载到接收者或通知上。

扩展包渠道 ​

如果用户希望在 Discord 等 Laravel 尚未内置支持的平台上接收通知,可以通过扩展包添加渠道。通知可以像构建邮件和短信一样为该渠道构建消息。

通过扩展包渠道发送 ​

在通知的 #[notification] 实现中,用 #[via(..)] 及渠道类型标记一个方法,即可通过扩展包渠道发送消息。例如,假设 discord_notifications 包提供 Discord 渠道,可向 webhook URL 发送 DiscordMessage:

rust
use discord_notifications::{Discord, DiscordMessage};
use laravel::notification;
use laravel::notification::Receives;

#[notification]
impl InvoicePaid {
    // `mail` 和 `sms` 与之前相同……

    #[via(Discord)]
    fn discord(&self, _user: &User) -> DiscordMessage {
        DiscordMessage::new(format!("Invoice #{} is paid.", self.invoice.id))
    }
}

接收者需实现 Receives<Discord>,其 route 方法返回扩展包定义的目标值。假设用户表中有可为空的 discord_webhook_url 列:

rust
impl Receives<Discord> for User {
    fn route(&self) -> Option<String> {
        self.discord_webhook_url.clone()
    }
}

与内置渠道一样,只要 Receives<Discord>::route 返回 Some,就默认会包含该扩展包渠道。如果通知定义了 channels 方法来按接收者选择渠道,请将扩展包渠道类型传给 channels.add,以将它纳入投递范围:

rust
use discord_notifications::Discord;
use laravel::notification;
use laravel::notification::{Mail, Selected};

#[notification]
impl InvoicePaid {
    // `mail`、`sms` 和 `discord` 与之前相同……

    fn channels(&self, user: &User, channels: &mut Selected<Self, User>) {
        channels.add(Mail);

        if user.discord_alerts {
            channels.add(Discord);
        }
    }
}

传给 channels.add 的渠道类型会经过类型检查。只有通知定义了 #[via(Discord)] 方法且接收者实现了 Receives<Discord> 才能通过编译。

编写渠道 ​

渠道是一个单元结构体,其 impl 块带有 #[notification::channel] 属性。impl 中的异步 send 函数接收目标路由和消息,在提供商接受消息后返回。下面是扩展包可提供的 Discord 渠道:

rust
use laravel::http::client;
use laravel::notification;
use serde::{Deserialize, Serialize};

#[derive(Clone, Copy)]
pub struct Discord;

#[derive(Serialize, Deserialize)]
pub struct DiscordMessage {
    pub content: String,
}

impl DiscordMessage {
    pub fn new(content: impl Into<String>) -> Self {
        Self { content: content.into() }
    }
}

#[notification::channel(name = "discord")]
impl Discord {
    async fn send(webhook_url: String, message: DiscordMessage) -> laravel::Result<()> {
        client::post(webhook_url).json(&message).ensure_successful().await?;

        Ok(())
    }

    fn check(message: &DiscordMessage) -> laravel::Result<()> {
        if message.content.chars().count() > 2000 {
            return Err(laravel::abort_with(
                500,
                "a Discord message holds at most 2,000 characters",
            ));
        }

        Ok(())
    }
}

send 的参数类型决定渠道的路由和消息类型。由于队列任务需要存储它们,两者都必须实现 Serialize 和 Deserialize。send 在应用上下文中运行,因此可以读取配置及解析服务,例如保存 API 令牌的配置节。

可选的 check 函数会在通知构建每条消息时执行检查,使提供商会拒绝的消息在发送代码和测试中就能失败,省去等到工作进程处理才发现的延迟。可用它实施提供商公布的限制,例如 Discord 的 2,000 字符上限。

将自定义渠道通知入队时,Laravel 会将渠道的 name 记录在任务载荷中,工作进程据此选择要调用的 send 函数。如果省略 name,Laravel 默认使用结构体的完整 Rust 模块路径,例如 discord_notifications::channels::Discord。

显式设置 name 可以使队列任务独立于模块布局。以后即使将结构体移至其他模块或重命名,已在队列中的任务仍能正常执行:

rust
#[notification::channel(name = "discord")]
impl DiscordWebhook {
    async fn send(webhook_url: String, message: DiscordMessage) -> laravel::Result<()> {
        // ...
    }
}

测试 ​

大多数测试只需要验证代码是否发起了通知。notification::fake() 记录通知,并跳过实际投递。它仍会按真实发送的流程构建和渲染每条消息,因此模板错误或无效电话号码都会导致测试失败:

rust
use laravel::model::create;
use laravel::notification;
use laravel::testing::prelude::*;

#[laravel::test]
async fn paying_an_invoice_notifies_the_customer(app: Application) -> laravel::Result<()> {
    let user = create!(User {
        name: "Taylor",
        email: "taylor@laravel.com",
        password: "password",
    })
    .await?;

    let invoice = create!(Invoice { user_id: user.id, total: 120_000 }).await?;

    let notifications = notification::fake();

    app.post(format!("/invoices/{}/pay", invoice.id)).await.assert_redirect();

    notifications.assert_sent_to_where::<InvoicePaid>(&user, |sent| {
        sent.notification().invoice.id == invoice.id && sent.sms().is_none()
    });

    Ok(())
}

传给判断函数的每个 SentNotification 都通过 notification() 暴露原始通知,可用 queued() 检查它是否进入队列。也可用 mail() 查看渲染后的邮件,或用 mailable::<M>() 检查用于构建该邮件的结构体:

rust
notifications.assert_sent_to_where::<InvoicePaid>(&user, |sent| {
    sent.queued()
        && sent
            .mail()
            .is_some_and(|email| email.subject() == format!("Invoice #{} is paid", invoice.id))
        && sent.mailable::<InvoicePaidEmail>().is_some_and(|mail| mail.name == user.name)
});

如果接收者跳过了某个渠道,该渠道的访问方法会返回 None。例如上面的 Taylor 没有电话号码,因此 sent.sms() 为 None。发送过短信时,可以用 sms() 查看消息:

rust
notifications.assert_sent_to_where::<InvoicePaid>(&user, |sent| {
    sent.sms().is_some_and(|sms| sms.text().contains("Thanks!"))
});

对于 Slack 和自定义扩展包渠道,请向 message::<C>() 传入渠道类型,检查构建好的消息:

rust
use discord_notifications::Discord;
use laravel::notification::Slack;

notifications.assert_sent_to_where::<InvoicePaid>(&team, |sent| {
    sent.message::<Slack>()
        .is_some_and(|message| message.text().contains(&format!("Invoice #{}", invoice.id)))
});

notifications.assert_sent_to_where::<InvoicePaid>(&user, |sent| {
    sent.message::<Discord>()
        .is_some_and(|message| message.content.contains(&format!("Invoice #{}", invoice.id)))
});

模拟工具提供以下断言:

方法断言或返回值
assert_sent::<T>()至少发送或入队过一个 T 类型的通知。
assert_sent_to::<T>(&notifiable)已为该接收者发送或入队 T 类型的通知。
assert_sent_to_where::<T>(&notifiable, predicate)有一个发给该接收者的 T 类型通知满足判断条件。
assert_not_sent_to::<T>(&notifiable)未为该接收者发送或入队 T 类型的通知。
assert_sent_where::<T>(predicate)有一个面向某位接收者的 T 类型通知满足判断条件。
assert_sent_times::<T>(count)T 类型的通知恰好面向 count 个接收者。
assert_not_sent::<T>()未发送或入队 T 类型的通知。
assert_nothing_sent()未发送或入队任何通知。
sent::<T>()按顺序返回 T 类型的每个 SentNotification 及其通知。

模拟工具同时记录同步发送和已入队的通知,可用 SentNotification::queued() 区分两者。

启用通知模拟时,通知不会到达邮件模拟工具或短信模拟工具。关闭通知模拟后,它们会将通知消息与普通邮件、短信一起记录。