nijens/sse

A Server Sent Events server implementation in PHP.

1.0.0 2019-11-07 14:00 UTC

This package is auto-updated.

Last update: 2024-12-10 17:38:47 UTC


README

Latest version on Packagist Software License Build Status

A Server-Sent Events server implementation in PHP.

For more information about SSE, see the MDN documentation.

Installation

Open a command console, enter your project directory and execute:

composer require nijens/sse

Usage

The SSE library functions with two main components:

  1. An event publisher implementation (eg. the DateTimeEventPublisher): Providing the events to be sent
  2. The SseKernel: Responsible for checking with the event publisher for new events and sending the events to the client (browser)

The following example shows how to initialize the SseKernel with an event publisher:

<?php

require __DIR__.'/../vendor/autoload.php';

use Nijens\Sse\Event\DateTimeEventPublisher;
use Nijens\Sse\SseKernel;
use Symfony\Component\HttpFoundation\Request;

$eventPublisher = new DateTimeEventPublisher('date-time');

$kernel = new SseKernel($eventPublisher);

$request = Request::createFromGlobals();
$response = $kernel->handle($request);

$response->send();

Integrating the SseKernel inside a Symfony controller

When you're using the Symfony Framework to create your application, you're still able to use the SseKernel implementation inside a controller.

The following example shows a crude implementation of the SseKernel inside a controller:

<?php

namespace App\Controller;

use Nijens\Sse\Event\DateTimeEventPublisher;
use Nijens\Sse\SseKernel;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\StreamedResponse;

class SseController
{
    public function __invoke(Request $request): StreamedResponse
    {
        $eventPublisher = new DateTimeEventPublisher('date-time');

        $kernel = new SseKernel($eventPublisher);

        return $kernel->handle($request);
    }
}

Optionally, you could use Dependency Injection to change the kernel and event publisher to services.

Creating your own event publisher

This library provides the following event publishers:

  • DateTimeEventPublisher: A working example, providing the current time as event
  • TransportEventPublisher: A event publisher implementation for implementing a transport (eg. MySQL database implementation)

You're able to create your own event publisher implementation by implementing the EventPublisherInterface or ConnectedClientEventPublisherInterface.

If you only want read the events from a database or other storage, it is recommended to create a TransportInterface implementation for the TransportEventPublisher.

Credits and acknowledgements

Also see the list of contributors who participated in this project.

License

The SSE package is licensed under the MIT License. Please see the LICENSE file for details.