Symfony Mercure Component

repository·main·Indexed 19 days ago

https://github.com/symfony/mercure

A PHP component that implements the publisher side of the Mercure protocol, enabling applications to push real-time data updates to web browsers and HTTP clients via a Mercure Hub.

Tokens
604
Snippets
2
Records
2
Agent score
16%

What's inside symfony/mercure

  1. Quickstart: Publish an update to a Mercure Hub

    main

    To publish real-time updates, you need to configure a Hub instance. This requires the Hub's URL and a TokenProvider that generates valid JWTs for authentication.

    1. Define your HUB_URL and JWT_SECRET.
    2. Create a LcobucciFactory using your secret.
    3. Create a FactoryTokenProvider (passing the factory and the topics you wish to publish to, e.g., ['*'] for all topics).
    4. Instantiate the Hub with the URL and provider.
    5. Use $hub->publish() with a new Update object containing the target topic (URL) and the payload.
    // change these values accordingly to your hub installation
    const HUB_URL = 'https://demo.mercure.rocks/.well-known/mercure';
    const JWT_SECRET = '!ChangeThisMercureHubJWTSecretKey!';
    
    // Set up the JWT token provider
    // Alternatively, you can use the \Symfony\Component\Mercure\Jwt\StaticTokenProvider if you already have a JWT token
    $jwFactory = new \Symfony\Component\Mercure\Jwt\LcobucciFactory(JWT_SECRET);
    $provider = new \Symfony\Component\Mercure\Jwt\FactoryTokenProvider($jwFactory, publish: ['*']);
    
    $hub = new \Symfony\Component\Mercure\Hub(HUB_URL, $provider);
    
    // Serialize the update, and dispatch it to the hub, that will broadcast it to the clients
    $id = $hub->publish(new \Symfony\Component\Mercure\Update('https://example.com/books/1.jsonld', 'Hi from Symfony!'));
  2. Install the Mercure Component

    main

    To use the Mercure component in your project, you need to install the component itself along with lcobucci/jwt to handle JWT token generation for the Mercure Hub.

    $ composer require symfony/mercure lcobucci/jwt