A Server-Sent Events server implementation in PHP.
For more information about SSE, see the MDN documentation.
Open a command console, enter your project directory and execute:
composer require nijens/sse
The SSE library functions with two main components:
- An event publisher implementation (eg. the
DateTimeEventPublisher
): Providing the events to be sent - 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();
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.
This library provides the following event publishers:
DateTimeEventPublisher
: A working example, providing the current time as eventTransportEventPublisher
: 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
.
- Author: Niels Nijens
Also see the list of contributors who participated in this project.
The SSE package is licensed under the MIT License. Please see the LICENSE file for details.