Skip to content

Symfony UX Notify

Edit this page

Symfony UX Notify is a Symfony bundle integrating server-sent native notifications in Symfony applications using Mercure. It is part of the Symfony UX initiative.

Installation

Caution

Before you start, make sure you have StimulusBundle configured in your app.

Install the bundle using Composer and Symfony Flex:

1
$ composer require symfony/ux-notify

If you're using WebpackEncore, install your assets and restart Encore (not needed if you're using AssetMapper):

1
2
$ npm install --force
$ npm run watch

Usage

To use Symfony UX Notify you must have a running Mercure server and a properly configured notifier transport:

1
2
3
4
5
# config/packages/notifier.yaml
framework:
    notifier:
        chatter_transports:
           myMercureChatter: '%env(MERCURE_DSN)%'

Then, you can inject the NotifierInterface service and send messages on the chat/myMercureChatter channel:

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;
    }
}

The chat/flash-sales is the Mercure topic the message will be sent to. The final step is to "listen" to that topic and trigger the notifications in the user's browser. To do that, call the stream_notifications() Twig function anywhere on the page:

1
{{ stream_notifications(['/chat/flash-sales']) }}

Note

Calling stream_notifications() without a parameter will default to the https://symfony.com/notifier topic.

Enjoy your server-sent native notifications!

Example of a native notification

Extend the Stimulus Controller

Symfony UX Notify allows you to extend its default behavior using a custom Stimulus controller:

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
            });
        });
    }
}

Then in your render call, add your controller as an HTML attribute:

1
{{ stream_notifications(options = {'data-controller': 'mynotify'}) }}

Using another Mercure hub

Symfony UX Notify can be configured to specify the Mercure hub to use:

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

Backward Compatibility promise

This bundle aims at following the same Backward Compatibility promise as the Symfony framework: https://symfony.com/doc/current/contributing/code/bc.html

This work, including the code samples, is licensed under a Creative Commons BY-SA 3.0 license.
TOC
    Version