Skip to content
  • About
    • What is Symfony?
    • Community
    • News
    • Contributing
    • Support
  • Documentation
    • Symfony Docs
    • Symfony Book
    • Screencasts
    • Symfony Bundles
    • Symfony Cloud
    • Training
  • Services
    • Platform.sh for Symfony Best platform to deploy Symfony apps
    • SymfonyInsight Automatic quality checks for your apps
    • Symfony Certification Prove your knowledge and boost your career
    • SensioLabs Professional services to help you with Symfony
    • Blackfire Profile and monitor performance of your apps
  • Other
  • Blog
  • Download
sponsored by
  1. Home
  2. Documentation
  3. Bundles
  4. Symfony UX Notify

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
    Online exam, become Symfony certified today

    Online exam, become Symfony certified today

    Save your teams and projects before they sink

    Save your teams and projects before they sink

    Version:

    Table of Contents

    • Installation
    • Usage
      • Extend the Stimulus Controller
      • Using another Mercure hub
    • Backward Compatibility promise

    Symfony footer

    Avatar of Daniel Gorgan, a Symfony contributor

    Thanks Daniel Gorgan for being a Symfony contributor

    2 commits • 19 lines changed

    View all contributors that help us make Symfony

    Become a Symfony contributor

    Be an active part of the community and contribute ideas, code and bug fixes. Both experts and newcomers are welcome.

    Learn how to contribute

    Symfony™ is a trademark of Symfony SAS. All rights reserved.

    • What is Symfony?

      • What is Symfony?
      • Symfony at a Glance
      • Symfony Components
      • Symfony Releases
      • Security Policy
      • Logo & Screenshots
      • Trademark & Licenses
      • symfony1 Legacy
    • Learn Symfony

      • Symfony Docs
      • Symfony Book
      • Reference
      • Bundles
      • Best Practices
      • Training
      • eLearning Platform
      • Certification
    • Screencasts

      • Learn Symfony
      • Learn PHP
      • Learn JavaScript
      • Learn Drupal
      • Learn RESTful APIs
    • Community

      • Symfony Community
      • SymfonyConnect
      • Events & Meetups
      • Projects using Symfony
      • Contributors
      • Symfony Jobs
      • Backers
      • Code of Conduct
      • Downloads Stats
      • Support
    • Blog

      • All Blog Posts
      • A Week of Symfony
      • Case Studies
      • Cloud
      • Community
      • Conferences
      • Diversity
      • Living on the edge
      • Releases
      • Security Advisories
      • Symfony Insight
      • Twig
      • SensioLabs Blog
    • Services

      • SensioLabs services
      • Train developers
      • Manage your project quality
      • Improve your project performance
      • Host Symfony projects

      Powered by

    Follow Symfony