Create real-time updates using Server-sent Events and libSSE

When I first learn node.js, I learned how to use socket.io, a node.js module for real-time communication between the client and server. However, when I’m going back coding PHP for a while, I started to figure out only few PHP libraries offered this functions and the techniques they uses are old (AJAX Streaming, Forever <iframe>, etc.). One day I found a new technique called Server-sent Events and it’s pretty easy to implant. I have an idea of creating an interface for¬†Server-sent Events in order to speed up development and make it easier to use. libSSE is the library I’ve create just for this and it’s event-based which means data is sent only when an event happens. It also has some utility classes for communicate with other PHP scripts.

Here’s the library:¬†https://github.com/licson0729/libSSE-php

It’s pretty easy to use. Here’s an example.

<?php
require_once('./src/libsse.php');//include the library

//create the event handler
//every event must inherit the base event class SSEEvent
class YourEventHandler extends SSEEvent {
    public function update(){
        //Here's the place to send data
        return time();
    }
    public function check(){
        //Here's the place to check when the data needs update
        return time() % 20 === 0;
    }
}

$sse = new SSE();//create a libSSE instance
//register your event handler
$sse->addEventListener(
    'event_name', //The name of the event
    new YourEventHandler() //The event handler defined above
);
$sse->start();//start the event loop

On the client-side you need to set up an EventSource object to listen event from server.

var sse = new EventSource('path/to/your/sse/script.php');
sse.addEventListener('event_name',function(e){
    var data = e.data;
    //handle your data here
},false);

Remember that Server-sent Events is still a new standard and not all browsers supports it. However, polyfills are available for them. Hope you like it and find it useful.