Symfony UX Notify
Symfony UX Notify 是一個 Symfony 套件,整合了伺服器發送的 原生通知,在 Symfony 應用程式中使用 Mercure。 它是 Symfony UX 計畫的一部分。
安裝
注意
在開始之前,請確保您的應用程式中已配置 StimulusBundle。
使用 Composer 和 Symfony Flex 安裝套件
1
$ composer require symfony/ux-notify
如果您使用 WebpackEncore,請安裝您的 assets 並重新啟動 Encore (如果您使用 AssetMapper 則不需要)
1 2
$ npm install --force
$ npm run watch
用法
要使用 Symfony UX Notify,您必須有一個 正在運行的 Mercure 伺服器和一個正確配置的通知器傳輸
1 2 3 4 5
# config/packages/notifier.yaml
framework:
notifier:
chatter_transports:
myMercureChatter: '%env(MERCURE_DSN)%'
然後,您可以注入 NotifierInterface
服務,並在 chat/myMercureChatter
頻道上發送訊息
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24
// ...
use Symfony\Component\Notifier\ChatterInterface;
use Symfony\Component\Notifier\Message\ChatMessage;
#[AsCommand(name: 'app:flash-sales:announce')]
class AnnounceFlashSalesCommand extends Command
{
public function __construct(private ChatterInterface $chatter)
{
parent::__construct();
}
protected function execute(InputInterface $input, OutputInterface $output): int
{
$message = (new ChatMessage(
'Flash sales has been started!',
new MercureOptions(['/chat/flash-sales'])
))->transport('myMercureChatter');
$this->chatter->send($message);
return 0;
}
}
chat/flash-sales
是訊息將被發送到 Mercure 主題。 最後一步是「監聽」該主題並在用戶的瀏覽器中觸發通知。 為此,請在頁面上的任何位置調用 stream_notifications()
Twig 函數
1
{{ stream_notifications(['/chat/flash-sales']) }}
注意
調用不帶參數的 stream_notifications()
將默認設定為 https://symfony.dev.org.tw/notifier
主題。
享受您的伺服器發送的原生通知!

擴展 Stimulus 控制器
Symfony UX Notify 允許您使用自定義 Stimulus 控制器擴展其默認行為
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
// assets/controllers/mynotify_controller.js
import { Controller } from '@hotwired/stimulus';
export default class extends Controller {
initialize() {
// guarantees "this" refers to this object in _onConnect
this._onConnect = this._onConnect.bind(this);
}
connect() {
this.element.addEventListener('notify:connect', this._onConnect);
}
disconnect() {
// You should always remove listeners when the controller is disconnected to avoid side effects
this.element.removeEventListener('notify:connect', this._onConnect);
}
_onConnect(event) {
// Event sources have just been created
console.log(event.detail.eventSources);
event.detail.eventSources.forEach((eventSource) => {
eventSource.addEventListener('message', (event) => {
console.log(event); // You can add custom behavior on each event source
});
});
}
}
然後在您的渲染調用中,將您的控制器添加為 HTML 屬性
1
{{ stream_notifications(options = {'data-controller': 'mynotify'}) }}
使用另一個 Mercure hub
Symfony UX Notify 可以配置為指定要使用的 Mercure hub
1 2 3 4
# config/packages/notify.yaml
notify:
# Specifies the Mercure hub to use. Defaults to "mercure.hub.default"
mercure_hub: mercure.hub.custom
向後相容性承諾
此套件旨在遵循與 Symfony 框架相同的向後相容性承諾: https://symfony.dev.org.tw/doc/current/contributing/code/bc.html