建立和發送通知
安裝
目前的網路應用程式使用許多不同的管道來發送訊息給使用者 (例如簡訊、Slack 訊息、電子郵件、推播通知等)。Symfony 中的 Notifier 元件是對所有這些管道的抽象化。它提供了一種動態的方式來管理訊息的發送方式。使用以下方式安裝 Notifier
1
$ composer require symfony/notifier
管道
管道指的是可以傳遞通知的不同媒介。這些管道包括電子郵件、簡訊、聊天服務、推播通知等。每個管道都可以透過使用傳輸方式與不同的供應商 (例如 Slack 或 Twilio SMS) 整合。
通知器元件支援以下管道
- 簡訊管道 透過簡訊將通知發送到手機;
- 聊天管道 將通知發送到聊天服務,例如 Slack 和 Telegram;
- 電子郵件管道 整合了 Symfony Mailer;
- 瀏覽器管道使用 flash 訊息。
- 推播管道 透過推播通知將通知發送到手機和瀏覽器。
- 桌面管道 在同一主機上顯示桌面通知。
7.2
Desktop
管道在 Symfony 7.2 中引入。
簡訊管道
簡訊管道使用 Texter 類別將簡訊發送到手機。此功能需要訂閱第三方服務來發送簡訊。Symfony 提供了與幾個流行的簡訊服務的整合
警告
如果任何 DSN 值包含 URI 中視為特殊的字元 (例如 : / ? # [ ] @ ! $ & ' ( ) * + , ; =
),您必須對它們進行編碼。請參閱 RFC 3986 以取得保留字元的完整列表,或使用 urlencode 函數對它們進行編碼。
服務 | |
---|---|
46elks | 安裝:composer require symfony/forty-six-elks-notifier DSN: forty-six-elks://API_USERNAME:API_PASSWORD@default?from=FROM Webhook 支援:否 |
AllMySms | 安裝:composer require symfony/all-my-sms-notifier DSN: allmysms://LOGIN:APIKEY@default?from=FROM Webhook 支援:否 |
AmazonSns | 安裝:composer require symfony/amazon-sns-notifier DSN: sns://ACCESS_KEY:SECRET_KEY@default?region=REGION Webhook 支援:否 |
Bandwidth | 安裝:composer require symfony/bandwidth-notifier DSN: bandwidth://USERNAME:PASSWORD@default?from=FROM&account_id=ACCOUNT_ID&application_id=APPLICATION_ID&priority=PRIORITY Webhook 支援:否 |
Brevo | 安裝:composer require symfony/brevo-notifier DSN: brevo://API_KEY@default?sender=SENDER Webhook 支援:否 |
Clickatell | 安裝:composer require symfony/clickatell-notifier DSN: clickatell://ACCESS_TOKEN@default?from=FROM Webhook 支援:否 |
ContactEveryone | 安裝:composer require symfony/contact-everyone-notifier DSN: contact-everyone://TOKEN@default?&diffusionname=DIFFUSION_NAME&category=CATEGORY Webhook 支援:否 |
Esendex | 安裝:composer require symfony/esendex-notifier DSN: esendex://USER_NAME:PASSWORD@default?accountreference=ACCOUNT_REFERENCE&from=FROM Webhook 支援:否 |
FakeSms | 安裝:composer require symfony/fake-sms-notifier DSN: fakesms+email://MAILER_SERVICE_ID?to=TO&from=FROM 或 fakesms+logger://default Webhook 支援:否 |
FreeMobile | 安裝:composer require symfony/free-mobile-notifier DSN: freemobile://LOGIN:API_KEY@default?phone=PHONE Webhook 支援:否 |
GatewayApi | 安裝:composer require symfony/gateway-api-notifier DSN: gatewayapi://TOKEN@default?from=FROM Webhook 支援:否 |
GoIP | 安裝:composer require symfony/go-ip-notifier DSN: goip://USERNAME:PASSWORD@HOST:80?sim_slot=SIM_SLOT Webhook 支援:否 |
Infobip | 安裝:composer require symfony/infobip-notifier DSN: infobip://AUTH_TOKEN@HOST?from=FROM Webhook 支援:否 |
Iqsms | 安裝:composer require symfony/iqsms-notifier DSN: iqsms://LOGIN:PASSWORD@default?from=FROM Webhook 支援:否 |
iSendPro | 安裝:composer require symfony/isendpro-notifier DSN: isendpro://ACCOUNT_KEY_ID@default?from=FROM&no_stop=NO_STOP&sandbox=SANDBOX Webhook 支援:否 |
KazInfoTeh | 安裝:composer require symfony/kaz-info-teh-notifier DSN: kaz-info-teh://USERNAME:PASSWORD@default?sender=FROM Webhook 支援:否 |
LightSms | 安裝:composer require symfony/light-sms-notifier DSN: lightsms://LOGIN:TOKEN@default?from=PHONE Webhook 支援:否 |
LOX24 | 安裝:composer require symfony/lox24-notifier DSN: lox24://USER:TOKEN@default?from=FROM Webhook 支援:否 |
Mailjet | 安裝:composer require symfony/mailjet-notifier DSN: mailjet://TOKEN@default?from=FROM Webhook 支援:否 |
MessageBird | 安裝:composer require symfony/message-bird-notifier DSN: messagebird://TOKEN@default?from=FROM Webhook 支援:否 |
MessageMedia | 安裝:composer require symfony/message-media-notifier DSN: messagemedia://API_KEY:API_SECRET@default?from=FROM Webhook 支援:否 |
Mobyt | 安裝:composer require symfony/mobyt-notifier DSN: mobyt://USER_KEY:ACCESS_TOKEN@default?from=FROM Webhook 支援:否 |
Nexmo | 安裝:composer require symfony/nexmo-notifier 已棄用,改用 Vonage (見下方) |
Octopush | 安裝:composer require symfony/octopush-notifier DSN: octopush://USERLOGIN:APIKEY@default?from=FROM&type=TYPE Webhook 支援:否 |
OrangeSms | 安裝:composer require symfony/orange-sms-notifier DSN: orange-sms://CLIENT_ID:CLIENT_SECRET@default?from=FROM&sender_name=SENDER_NAME Webhook 支援:否 |
OvhCloud | 安裝:composer require symfony/ovh-cloud-notifier DSN: ovhcloud://APPLICATION_KEY:APPLICATION_SECRET@default?consumer_key=CONSUMER_KEY&service_name=SERVICE_NAME Webhook 支援:否 |
Plivo | 安裝:composer require symfony/plivo-notifier DSN: plivo://AUTH_ID:AUTH_TOKEN@default?from=FROM Webhook 支援:否 |
Primotexto | 安裝:composer require symfony/primotexto-notifier DSN: primotexto://API_KEY@default?from=FROM Webhook 支援:否 |
Redlink | 安裝:composer require symfony/redlink-notifier DSN: redlink://API_KEY:APP_KEY@default?from=SENDER_NAME&version=API_VERSION Webhook 支援:否 |
RingCentral | 安裝:composer require symfony/ring-central-notifier DSN: ringcentral://API_TOKEN@default?from=FROM Webhook 支援:否 |
Sendberry | 安裝:composer require symfony/sendberry-notifier DSN: sendberry://USERNAME:PASSWORD@default?auth_key=AUTH_KEY&from=FROM Webhook 支援:否 |
Sendinblue | 安裝:composer require symfony/sendinblue-notifier DSN: sendinblue://API_KEY@default?sender=PHONE Webhook 支援:否 |
Sms77 | 安裝:composer require symfony/sms77-notifier DSN: sms77://API_KEY@default?from=FROM Webhook 支援:否 |
SimpleTextin | 安裝:composer require symfony/simple-textin-notifier DSN: simpletextin://API_KEY@default?from=FROM Webhook 支援:否 |
Sinch | 安裝:composer require symfony/sinch-notifier DSN: sinch://ACCOUNT_ID:AUTH_TOKEN@default?from=FROM Webhook 支援:否 |
Sipgate | 安裝:composer require symfony/sipgate-notifier DSN: sipgate://TOKEN_ID:TOKEN@default?senderId=SENDER_ID Webhook 支援:否 |
SmsSluzba | 安裝:composer require symfony/sms-sluzba-notifier DSN: sms-sluzba://USERNAME:PASSWORD@default Webhook 支援:否 |
Smsapi | 安裝:composer require symfony/smsapi-notifier DSN: smsapi://TOKEN@default?from=FROM Webhook 支援:否 |
Smsbox | 安裝:composer require symfony/smsbox-notifier DSN: smsbox://APIKEY@default?mode=MODE&strategy=STRATEGY&sender=SENDER Webhook 支援:否 |
SmsBiuras | 安裝:composer require symfony/sms-biuras-notifier DSN: smsbiuras://UID:API_KEY@default?from=FROM&test_mode=0 Webhook 支援:否 |
Smsc | 安裝:composer require symfony/smsc-notifier DSN: smsc://LOGIN:PASSWORD@default?from=FROM Webhook 支援:否 |
SMSense | 安裝:composer require smsense-notifier DSN: smsense://API_TOKEN@default?from=FROM Webhook 支援:否 |
SMSFactor | 安裝:composer require symfony/sms-factor-notifier DSN: sms-factor://TOKEN@default?sender=SENDER&push_type=PUSH_TYPE Webhook 支援:否 |
SpotHit | 安裝:composer require symfony/spot-hit-notifier DSN: spothit://TOKEN@default?from=FROM Webhook 支援:否 |
Sweego | 安裝:composer require symfony/sweego-notifier DSN: sweego://API_KEY@default?region=REGION&campaign_type=CAMPAIGN_TYPE Webhook 支援:是 |
Telnyx | 安裝:composer require symfony/telnyx-notifier DSN: telnyx://API_KEY@default?from=FROM&messaging_profile_id=MESSAGING_PROFILE_ID Webhook 支援:否 |
TurboSms | 安裝:composer require symfony/turbo-sms-notifier DSN: turbosms://AUTH_TOKEN@default?from=FROM Webhook 支援:否 |
Twilio | 安裝:composer require symfony/twilio-notifier DSN: twilio://SID:TOKEN@default?from=FROM Webhook 支援:是 |
Unifonic | 安裝:composer require symfony/unifonic-notifier DSN: unifonic://APP_SID@default?from=FROM Webhook 支援:否 |
Vonage | 安裝:composer require symfony/vonage-notifier DSN: vonage://KEY:SECRET@default?from=FROM Webhook 支援:是 |
Yunpian | 安裝:composer require symfony/yunpian-notifier DSN: yunpian://APIKEY@default Webhook 支援:否 |
提示
使用 Symfony 組態密鑰 安全地儲存您的 API 令牌。
提示
某些第三方傳輸方式在使用 API 時,支援透過 Webhook 進行狀態回呼。請參閱 Webhook 文件 以取得更多詳細資訊。
7.1
Smsbox
、SmsSluzba
、SMSense
、LOX24
和 Unifonic
整合在 Symfony 7.1 中引入。
7.2
Primotexto
、Sipgate
和 Sweego
整合在 Symfony 7.2 中引入。
若要啟用 texter,請在您的 .env
檔案中新增正確的 DSN,並設定 texter_transports
1 2
# .env
TWILIO_DSN=twilio://SID:TOKEN@default?from=FROM
1 2 3 4 5
# config/packages/notifier.yaml
framework:
notifier:
texter_transports:
twilio: '%env(TWILIO_DSN)%'
TexterInterface 類別允許您發送簡訊
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33
// src/Controller/SecurityController.php
namespace App\Controller;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Notifier\Message\SmsMessage;
use Symfony\Component\Notifier\TexterInterface;
use Symfony\Component\Routing\Attribute\Route;
class SecurityController
{
#[Route('/login/success')]
public function loginSuccess(TexterInterface $texter): Response
{
$options = (new ProviderOptions())
->setPriority('high')
;
$sms = new SmsMessage(
// the phone number to send the SMS message to
'+1411111111',
// the message
'A new login was detected!',
// optionally, you can override default "from" defined in transports
'+1422222222',
// you can also add options object implementing MessageOptionsInterface
$options
);
$sentMessage = $texter->send($sms);
// ...
}
}
send()
方法會傳回 SentMessage 類型的變數,其中提供訊息 ID 和原始訊息內容等資訊。
聊天管道
警告
如果任何 DSN 值包含 URI 中視為特殊的字元 (例如 : / ? # [ ] @ ! $ & ' ( ) * + , ; =
),您必須對它們進行編碼。請參閱 RFC 3986 以取得保留字元的完整列表,或使用 urlencode 函數對它們進行編碼。
聊天管道用於透過使用 Chatter 類別向使用者發送聊天訊息。Symfony 提供了與這些聊天服務的整合
服務 | 套件 | DSN |
---|---|---|
AmazonSns | symfony/amazon-sns-notifier |
sns://ACCESS_KEY:SECRET_KEY@default?region=REGION |
Bluesky | symfony/bluesky-notifier |
bluesky://USERNAME:PASSWORD@default |
Chatwork | symfony/chatwork-notifier |
chatwork://API_TOKEN@default?room_id=ID |
Discord | symfony/discord-notifier |
discord://TOKEN@default?webhook_id=ID |
FakeChat | symfony/fake-chat-notifier |
fakechat+email://default?to=TO&from=FROM 或 fakechat+logger://default |
Firebase | symfony/firebase-notifier |
firebase://USERNAME:PASSWORD@default |
GoogleChat | symfony/google-chat-notifier |
googlechat://ACCESS_KEY:ACCESS_TOKEN@default/SPACE?thread_key=THREAD_KEY |
LINE Bot | symfony/line-bot-notifier |
linebot://TOKEN@default?receiver=RECEIVER |
LINE Notify | symfony/line-notify-notifier |
linenotify://TOKEN@default |
symfony/linked-in-notifier |
linkedin://TOKEN:USER_ID@default |
|
Mastodon | symfony/mastodon-notifier |
mastodon://ACCESS_TOKEN@HOST |
Mattermost | symfony/mattermost-notifier |
mattermost://ACCESS_TOKEN@HOST/PATH?channel=CHANNEL |
Mercure | symfony/mercure-notifier |
mercure://HUB_ID?topic=TOPIC |
MicrosoftTeams | symfony/microsoft-teams-notifier |
microsoftteams://default/PATH |
RocketChat | symfony/rocket-chat-notifier |
rocketchat://TOKEN@ENDPOINT?channel=CHANNEL |
Slack | symfony/slack-notifier |
slack://TOKEN@default?channel=CHANNEL |
Telegram | symfony/telegram-notifier |
telegram://TOKEN@default?channel=CHAT_ID |
symfony/twitter-notifier |
twitter://API_KEY:API_SECRET:ACCESS_TOKEN:ACCESS_SECRET@default |
|
Zendesk | symfony/zendesk-notifier |
zendesk://EMAIL:TOKEN@SUBDOMAIN |
Zulip | symfony/zulip-notifier |
zulip://EMAIL:TOKEN@HOST?channel=CHANNEL |
7.1
Bluesky
整合在 Symfony 7.1 中引入。
7.2
LINE Bot
整合在 Symfony 7.2 中引入。
7.2
Gitter
整合已在 Symfony 7.2 中移除,因為該服務不再提供 API。
警告
預設情況下,如果您已安裝 Messenger 元件,通知將透過 MessageBus 發送。如果您沒有訊息消費者正在運行,訊息將永遠不會發送。
若要變更此行為,請新增以下組態以直接透過傳輸方式發送訊息
1 2 3 4
# config/packages/notifier.yaml
framework:
notifier:
message_bus: false
Chatter 使用 chatter_transports
設定進行組態
1 2
# .env
SLACK_DSN=slack://TOKEN@default?channel=CHANNEL
1 2 3 4 5
# config/packages/notifier.yaml
framework:
notifier:
chatter_transports:
slack: '%env(SLACK_DSN)%'
ChatterInterface 類別允許您向聊天服務發送訊息
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24
// src/Controller/CheckoutController.php
namespace App\Controller;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Notifier\ChatterInterface;
use Symfony\Component\Notifier\Message\ChatMessage;
use Symfony\Component\Routing\Attribute\Route;
class CheckoutController extends AbstractController
{
#[Route('/checkout/thankyou')]
public function thankyou(ChatterInterface $chatter): Response
{
$message = (new ChatMessage('You got a new invoice for 15 EUR.'))
// if not set explicitly, the message is sent to the
// default transport (the first one configured)
->transport('slack');
$sentMessage = $chatter->send($message);
// ...
}
}
send()
方法會傳回 SentMessage 類型的變數,其中提供訊息 ID 和原始訊息內容等資訊。
電子郵件管道
電子郵件管道使用 Symfony Mailer,使用特殊的 NotificationEmail 發送通知。需要安裝 Twig bridge 以及 Inky 和 CSS Inliner Twig 擴充功能
1
$ composer require symfony/twig-pack twig/cssinliner-extra twig/inky-extra
在此之後,設定郵件程式。您也可以設定預設的「寄件者」電子郵件地址,該地址將用於傳送通知電子郵件
1 2 3 4 5 6
# config/packages/mailer.yaml
framework:
mailer:
dsn: '%env(MAILER_DSN)%'
envelope:
sender: 'notifications@example.com'
推播管道
警告
如果任何 DSN 值包含 URI 中視為特殊的字元 (例如 : / ? # [ ] @ ! $ & ' ( ) * + , ; =
),您必須對它們進行編碼。請參閱 RFC 3986 以取得保留字元的完整列表,或使用 urlencode 函數對它們進行編碼。
推播管道用於使用 Texter 類別向使用者傳送通知。Symfony 提供了與這些推播服務的整合
服務 | 套件 | DSN |
---|---|---|
Engagespot | symfony/engagespot-notifier |
engagespot://API_KEY@default?campaign_name=CAMPAIGN_NAME |
Expo | symfony/expo-notifier |
expo://Token@default |
Novu | symfony/novu-notifier |
novu://API_KEY@default |
Ntfy | symfony/ntfy-notifier |
ntfy://default/TOPIC |
OneSignal | symfony/one-signal-notifier |
onesignal://APP_ID:API_KEY@default?defaultRecipientId=DEFAULT_RECIPIENT_ID |
PagerDuty | symfony/pager-duty-notifier |
pagerduty://TOKEN@SUBDOMAIN |
Pushover | symfony/pushover-notifier |
pushover://USER_KEY:APP_TOKEN@default |
Pushy | symfony/pushy-notifier |
pushy://API_KEY@default |
若要啟用 texter,請在您的 .env
檔案中新增正確的 DSN,並設定 texter_transports
7.1
Pushy 整合在 Symfony 7.1 中引入。
1 2
# .env
EXPO_DSN=expo://TOKEN@default
1 2 3 4 5
# config/packages/notifier.yaml
framework:
notifier:
texter_transports:
expo: '%env(EXPO_DSN)%'
桌面管道
桌面管道用於在使用 Texter 類別的相同主機上顯示本機桌面通知。目前,Symfony 已與以下供應商整合
供應商 | 套件 | DSN |
---|---|---|
JoliNotif | symfony/joli-notif-notifier |
jolinotif://default |
7.2
JoliNotif 橋接器在 Symfony 7.2 中引入。
如果您正在使用 Symfony Flex,安裝該套件也會建立必要的環境變數和組態。否則,您需要手動新增以下內容
- 在您的
.env
檔案中新增正確的 DSN
1 2
# .env
JOLINOTIF=jolinotif://default
- 更新 Notifier 組態以新增新的 texter 傳輸方式
1 2 3 4 5
# config/packages/notifier.yaml
framework:
notifier:
texter_transports:
jolinotif: '%env(JOLINOTIF)%'
現在您可以如下所示將通知傳送到您的桌面
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22
// src/Notifier/SomeService.php
use Symfony\Component\Notifier\Message\DesktopMessage;
use Symfony\Component\Notifier\TexterInterface;
// ...
class SomeService
{
public function __construct(
private TexterInterface $texter,
) {
}
public function notifyNewSubscriber(User $user): void
{
$message = new DesktopMessage(
'New subscription! 🎉',
sprintf('%s is a new subscriber', $user->getFullName())
);
$texter->send($message);
}
}
這些通知可以進一步自訂,並且根據您的作業系統,它們可能支援自訂聲音、圖示等功能
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
use Symfony\Component\Notifier\Bridge\JoliNotif\JoliNotifOptions;
// ...
$options = (new JoliNotifOptions())
->setIconPath('/path/to/icons/error.png')
->setExtraOption('sound', 'sosumi')
->setExtraOption('url', 'https://example.com');
$message = new DesktopMessage('Production is down', <<<CONTENT
❌ Server prod-1 down
❌ Server prod-2 down
✅ Network is up
CONTENT, $options);
$texter->send($message);
設定使用故障轉移或循環配置傳輸
除了設定一個或多個單獨的傳輸方式之外,您還可以利用特殊的 ||
和 &&
字元來實作故障轉移或循環配置傳輸
1 2 3 4 5 6 7 8 9 10
# config/packages/notifier.yaml
framework:
notifier:
chatter_transports:
# Send notifications to Slack and use Telegram if
# Slack errored
main: '%env(SLACK_DSN)% || %env(TELEGRAM_DSN)%'
# Send notifications to the next scheduled transport calculated by round robin
roundrobin: '%env(SLACK_DSN)% && %env(TELEGRAM_DSN)%'
建立 & 發送通知
若要傳送通知,請自動裝配 NotifierInterface (服務 ID notifier
)。此類別具有 send()
方法,可讓您將 Notification 傳送到 Recipient
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32
// src/Controller/InvoiceController.php
namespace App\Controller;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Notifier\Notification\Notification;
use Symfony\Component\Notifier\NotifierInterface;
use Symfony\Component\Notifier\Recipient\Recipient;
class InvoiceController extends AbstractController
{
#[Route('/invoice/create')]
public function create(NotifierInterface $notifier): Response
{
// ...
// Create a Notification that has to be sent
// using the "email" channel
$notification = (new Notification('New Invoice', ['email']))
->content('You got a new invoice for 15 EUR.');
// The receiver of the Notification
$recipient = new Recipient(
$user->getEmail(),
$user->getPhonenumber()
);
// Send the notification to the recipient
$notifier->send($notification, $recipient);
// ...
}
}
Notification
是透過使用兩個引數建立的:主旨和管道。管道指定應該使用哪個管道(或傳輸方式)來傳送通知。例如,['email', 'sms']
將向使用者傳送電子郵件和簡訊通知。
預設通知也具有 content()
和 emoji()
方法來設定通知內容和圖示。
Symfony 提供了以下接收者
- NoRecipient
- 這是預設值,當不需要有關接收者的資訊時很有用。例如,瀏覽器管道使用當前請求的 session flashbag;
- Recipient
- 這可以包含使用者的電子郵件地址和電話號碼。此接收者可用於所有管道(取決於它們是否實際設定)。
設定管道策略
除了在建立時指定目標管道之外,Symfony 還允許您使用通知重要性層級。更新組態以指定哪些管道應用於特定層級(使用 channel_policy
)
1 2 3 4 5 6 7 8 9 10 11 12 13 14
# config/packages/notifier.yaml
framework:
notifier:
# ...
channel_policy:
# Use SMS, Slack and email for urgent notifications
urgent: ['sms', 'chat/slack', 'email']
# Use Slack for highly important notifications
high: ['chat/slack']
# Use browser for medium and low notifications
medium: ['browser']
low: ['browser']
現在,每當通知的重要性設定為「high」時,它將使用 Slack 傳輸方式傳送
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
// ...
class InvoiceController extends AbstractController
{
#[Route('/invoice/create')]
public function invoice(NotifierInterface $notifier): Response
{
// ...
$notification = (new Notification('New Invoice'))
->content('You got a new invoice for 15 EUR.')
->importance(Notification::IMPORTANCE_HIGH);
$notifier->send($notification, new Recipient('wouter@example.com'));
// ...
}
}
自訂通知
您可以擴充 Notification
或 Recipient
基礎類別來自訂其行為。例如,您可以覆寫 getChannels()
方法,以便僅在發票價格非常高且接收者有電話號碼時才傳回 sms
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25
namespace App\Notifier;
use Symfony\Component\Notifier\Notification\Notification;
use Symfony\Component\Notifier\Recipient\RecipientInterface;
use Symfony\Component\Notifier\Recipient\SmsRecipientInterface;
class InvoiceNotification extends Notification
{
public function __construct(
private int $price,
) {
}
public function getChannels(RecipientInterface $recipient): array
{
if (
$this->price > 10000
&& $recipient instanceof SmsRecipientInterface
) {
return ['sms'];
}
return ['email'];
}
}
自訂通知訊息
每個管道都有自己的通知介面,您可以實作該介面來自訂通知訊息。例如,如果您想根據聊天服務修改訊息,請實作 ChatNotificationInterface 及其 asChatMessage()
方法
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29
// src/Notifier/InvoiceNotification.php
namespace App\Notifier;
use Symfony\Component\Notifier\Message\ChatMessage;
use Symfony\Component\Notifier\Notification\ChatNotificationInterface;
use Symfony\Component\Notifier\Notification\Notification;
use Symfony\Component\Notifier\Recipient\RecipientInterface;
class InvoiceNotification extends Notification implements ChatNotificationInterface
{
public function __construct(
private int $price,
) {
}
public function asChatMessage(RecipientInterface $recipient, ?string $transport = null): ?ChatMessage
{
// Add a custom subject and emoji if the message is sent to Slack
if ('slack' === $transport) {
$this->subject('You\'re invoiced '.strval($this->price).' EUR.');
$this->emoji("money");
return ChatMessage::fromNotification($this);
}
// If you return null, the Notifier will create the ChatMessage
// based on this notification as it would without this method.
return null;
}
}
也存在 SmsNotificationInterface、EmailNotificationInterface、PushNotificationInterface 和 DesktopNotificationInterface,以修改傳送到這些管道的訊息。
自訂瀏覽器通知 (Flash 訊息)
瀏覽器管道通知的預設行為是新增一個 flash message,並以 notification
作為其索引鍵。
但是,您可能更喜歡將通知的重要性層級對應到 flash message 的類型,以便您可以調整其樣式。
您可以透過使用您自己的 FlashMessageImportanceMapperInterface 實作覆寫預設的 notifier.flash_message_importance_mapper
服務來完成此操作,您可以在其中提供您自己的「重要性」到「警示層級」的對應。
Symfony 目前為 Bootstrap CSS 框架的典型警示層級提供了一個實作,您可以立即使用它來實作
1 2 3 4
# config/services.yaml
services:
notifier.flash_message_importance_mapper:
class: Symfony\Component\Notifier\FlashMessage\BootstrapFlashMessageImportanceMapper
測試通知器
Symfony 提供了一個 NotificationAssertionsTrait,它提供了用於測試 Notifier 實作的實用方法。您可以透過直接使用此類別或擴充 KernelTestCase 來從此類別中受益。
請參閱 測試文件 以取得可用斷言的清單。
停用傳送
在開發(或測試)時,您可能想要完全停用通知的傳遞。您可以透過強制 Notifier 僅在 dev
(和/或 test
)環境中,對所有已設定的 texter 和 chatter 傳輸方式使用 NullTransport
來完成此操作
1 2 3 4 5 6 7
# config/packages/dev/notifier.yaml
framework:
notifier:
texter_transports:
twilio: 'null://null'
chatter_transports:
slack: 'null://null'
使用事件
Notifier 元件的 Transport 類別允許您選擇性地透過事件掛鉤到生命週期中。
MessageEvent
事件
典型用途:在傳送訊息之前執行某些操作(例如記錄即將傳送的訊息,或顯示有關要執行的事件的某些資訊)。
就在傳送訊息之前,會分派事件類別 MessageEvent
。偵聽器會收到 MessageEvent 事件
1 2 3 4 5 6 7 8 9
use Symfony\Component\Notifier\Event\MessageEvent;
$dispatcher->addListener(MessageEvent::class, function (MessageEvent $event): void {
// gets the message instance
$message = $event->getMessage();
// log something
$this->logger(sprintf('Message with subject: %s will be send to %s', $message->getSubject(), $message->getRecipientId()));
});
FailedMessageEvent
事件
典型用途:在擲回例外之前執行某些操作(重試傳送訊息或記錄其他資訊)。
每當在傳送訊息時擲回例外時,就會分派事件類別 FailedMessageEvent
。偵聽器可以在擲回例外之前執行任何有用的操作。
偵聽器會收到 FailedMessageEvent 事件
1 2 3 4 5 6 7 8 9 10 11 12
use Symfony\Component\Notifier\Event\FailedMessageEvent;
$dispatcher->addListener(FailedMessageEvent::class, function (FailedMessageEvent $event): void {
// gets the message instance
$message = $event->getMessage();
// gets the error instance
$error = $event->getError();
// log something
$this->logger(sprintf('The message with subject: %s has not been sent successfully. The error is: %s', $message->getSubject(), $error->getMessage()));
});
SentMessageEvent
事件
典型用途:在訊息成功傳送時執行某些操作(例如擷取傳送訊息時傳回的 ID)。
在訊息成功傳送後,會分派事件類別 SentMessageEvent
。偵聽器會收到 SentMessageEvent 事件
1 2 3 4 5 6 7 8 9
use Symfony\Component\Notifier\Event\SentMessageEvent;
$dispatcher->addListener(SentMessageEvent::class, function (SentMessageEvent $event): void {
// gets the message instance
$message = $event->getMessage();
// log something
$this->logger(sprintf('The message has been successfully sent and has id: %s', $message->getMessageId()));
});