• Stars
    star
    106
  • Rank 325,871 (Top 7 %)
  • Language
    PHP
  • License
    MIT License
  • Created almost 13 years ago
  • Updated almost 7 years ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

A PHP 5.3 library for creating an EventSource stream.

EventSource

A PHP 5.3 library for creating an EventSource stream.

EventSource or Server-Sent-Events is a W3C specification that defines a protocol and an API for pushing data from the server to the client. This library is a server-side implementation of this protocol.

It is designed to be transport agnostic, allowing you to use it with apache directly or with other webservers, such as mongrel2.

Build Status

Fetch

The recommended way to install EventSource is through composer.

Just create a composer.json file for your project:

{
    "require": {
        "igorw/event-source": "1.0.*"
    }
}

And run these two commands to install it:

$ curl -s http://getcomposer.org/installer | php
$ php composer.phar install

Now you can add the autoloader, and you will have access to the library:

<?php
require 'vendor/autoload.php';

Usage

The first thing you need to do is output the EventSource headers, so that the client knows it's talking to an EventSource server.

<?php

use Igorw\EventSource\Stream;

foreach (Stream::getHeaders() as $name => $value) {
    header("$name: $value");
}

After that you create a Stream which provides a nice API for creating events. Once you call flush, all queued events are sent to the client.

This example will send a new event every 2 seconds.

<?php

use Igorw\EventSource\Stream;

$stream = new Stream();

while (true) {
    $stream
        ->event()
            ->setData("Hello World")
        ->end()
        ->flush();
    
    sleep(2);
}

And an example JavaScript client:

var stream = new EventSource('stream.php');

stream.addEventListener('message', function (event) {
    console.log(event.data);
});

Advanced

Last event id

When your events have ids, the client will send a Last-Event-ID header on reconnection. You can read this value and re-send any events that occured after the one provided by the user.

<?php

$lastId = filter_input(INPUT_SERVER, 'HTTP_LAST_EVENT_ID');

if ($lastId) {
    $buffer = getMessagesAfter($lastId);

    foreach ($buffer as $message) {
        $stream->event()
            ->setId($message['id'])
            ->setData($message['data']);
    }

    $stream->flush();
}

Event namespacing

You can namespace events by using the setEvent method on the event. This allows you to bind to those event types specifically on the client side.

Here is a stream that sends two events. One of type foo and one of type bar.

<?php

$stream
    ->event()
        ->setEvent('foo')
        ->setData($message['data']);
    ->end()
    ->event()
        ->setEvent('bar')
        ->setData($message['data']);
    ->end()
    ->flush();

On the client you bind to that event instead of the generic message one. Do note that the message event will not catch these messages.

var stream = new EventSource('stream.php');

stream.addEventListener('foo', function (event) {
    console.log('Received event foo!');
});

stream.addEventListener('bar', function (event) {
    console.log('Received event bar!');
});

Sending JSON

In most applications you will want to send more complex data as opposed to simple strings. The recommended way of doing this is to use the JSON format. It can encode and decode nested structures quite well.

On the server side, simply use the json_encode function to encode a value:

<?php

$data = array('userIds' => array(21, 43, 127));

$stream
    ->event()
        ->setData(json_encode($data));
    ->end()
    ->flush();

On the client side, you can use JSON.parse to decode it. For old browsers, where JSON is not available, see json2.js.

var stream = new EventSource('stream.php');

stream.addEventListener('message', function (event) {
    var data = JSON.parse(event.data);
    console.log('User IDs: '+data.userIds.join(', '));
});

Custom handler

By default the library will assume you are running in a traditional apache-like environment. This means that output happens through echo. If you are using a server that handles web output in a different way (eg. app server), then you will want to change this.

A handler is simply a function that takes a chunk (a single event) and sends it to the client. You can define it as a lambda. Here is the default handler:

<?php

$handler = function ($chunk) {
    echo $chunk;
    ob_flush();
    flush();
};

You just pass it to the constructor of the stream:

<?php

$stream = new Stream($handler);

PHP time limit

In some setups it may be required to remove the time limit of the script. If you are having problems with your script dying after 30 or 60 seconds, add this line.

<?php
set_time_limit(0);

Polyfill

Most old browsers have not implemented EventSource yet. Luckily there is a polyfill available, that allows them to be used in a wider range of browsers.

Tests

$ phpunit

License

MIT, see LICENSE.

More Repositories

1

evenement

Événement is a very simple event dispatching library for PHP.
PHP
1,239
star
2

retry

A tiny library for retrying failing operations.
PHP
542
star
3

get-in

Functions for for hash map (assoc array) traversal.
PHP
370
star
4

ConfigServiceProvider

A config ServiceProvider for Silex with support for php, json and yaml.
PHP
216
star
5

yolo

The microframework with swag.
PHP
201
star
6

IgorwFileServeBundle

Symfony2 Bundle for serving protected files.
PHP
167
star
7

doucheswag

Swag for douchebags.
PHP
135
star
8

naegleria

A brainfuck compiler written in PHP. Also, a brain-eating amoeba.
PHP
89
star
9

compose

Function composition.
PHP
84
star
10

reasoned-php

A miniKanren in PHP.
Hack
74
star
11

trashbin

simple pastebin written in PHP
PHP
72
star
12

galapagos

Evolutionary language transformation.
PHP
72
star
13

CgiHttpKernel

Adapter from HttpKernelInterface to CGI.
PHP
60
star
14

composer-yaml

Tool to convert from composer.yml to composer.json.
PHP
58
star
15

silex-examples

Examples of Silex apps.
PHP
58
star
16

smaug

Here be dragons.
PHP
44
star
17

edn

Extensible Data Notation Parser.
PHP
42
star
18

stack-oauth

OAuth stack middleware.
PHP
38
star
19

turing-php

Turing machine emulator in PHP.
PHP
30
star
20

balrog

The tiny static site generator written in lisphp.
PHP
29
star
21

lambda-php

Lambda calculus interpreter in PHP.
PHP
22
star
22

ilias

Naive LISP implementation in PHP.
PHP
22
star
23

SocketServer

Stream-powered library for creating a socket server in PHP.
PHP
21
star
24

fab-symfony-console

Make symfony console output FABULOUS!
PHP
21
star
25

chicken-php

Chicken VM written in PHP.
PHP
21
star
26

whitespace-php

It's the little machine that you cannot see!
PHP
19
star
27

middleware

Demo of HttpKernel middlewares.
PHP
18
star
28

conway-php

Conway's Game of Life in PHP.
PHP
18
star
29

phpunit-phar

package phpunit as a standalone phar file.
PHP
17
star
30

webserver-zceu

PHP
17
star
31

websockets-talk

Samples from the WebSockets talk.
JavaScript
17
star
32

dev-zero

/dev/zero emulator, provides a large supply of zeroes.
PHP
12
star
33

FcgiHttpKernel

Adapter from HttpKernelInterface to FastCGI.
PHP
12
star
34

brainfuck-php

Brainfuck implementation.
PHP
8
star
35

dnsresolv

Foobar DnsResolv, based on Silex.
PHP
8
star
36

befunge-php

Befunge-98 implementation.
PHP
7
star
37

cute-little-interpreters

ROBOTS! IN YOUR COMPUTER!
PHP
7
star
38

clusterstream

A stream of the universe.
PHP
6
star
39

weblog

Weblog on igor.io.
CSS
5
star
40

matelight-blm

Bring back the old Blinkenlights to Mate Light.
PHP
5
star
41

rpn

Calculator.
PHP
4
star
42

wsm

Whitespace Assembly Language
PHP
4
star
43

composer-version-invalidation

A test project for composer version invalidation.
4
star
44

lusp

A lil' Lisp.
PHP
4
star
45

realtime-examples

Examples of real-time apps using websockets and eventstream.
PHP
4
star
46

webpaper

paper on the web
JavaScript
4
star
47

git-search

Index a number of git repositories into elasticsearch, view via web interface.
PHP
3
star
48

modcasts

phpbb modding screencasts
PHP
3
star
49

silencium

Multiplayer kick-ass taboo
Ruby
3
star
50

pip-phar

Compiles pip into a phar archive that can serve Silex apps.
PHP
3
star
51

playground

Shell
2
star
52

phpbb

Popular open-source bulletin board written in PHP
PHP
2
star
53

whyyy.computer

2
star
54

notponies

idea collection system based on phpBB
PHP
2
star
55

NelmioHelloBundle

PHP
2
star
56

polysolv

Recursive implementation of Newton's method for finding polynomial roots.
Java
2
star
57

craplog

This is one of the crappiest blogs you will ever find.
PHP
2
star
58

webserver-talk

PHP
2
star
59

ascraeus-foobar-extension

Foobar extension for the upcoming phpBB 3.1.
PHP
2
star
60

phpbb-github_profile_link

A phpBB 3.0 modification to let users specify their GitHub profile.
PHP
2
star
61

nbsp

2
star
62

septopus

Septopus is a sucky vocab trainer written in java.
Java
1
star
63

automata-php

Kleine automaten.
PHP
1
star
64

dotfiles

geeky unix shell config.
Vim Script
1
star
65

slave

automated phpBB installation, that's right.
PHP
1
star
66

createjs-presence-server

Sample implementation of a presence server for createjs.
1
star
67

bitserv

git-based wiki built on sinatra
Ruby
1
star
68

clj-polysolv

Recursive implementation of Newton's method for finding polynomial roots.
Clojure
1
star
69

ultragraph

Java application to simulate basic graph theory algorithms.
Java
1
star
70

bitserv-example

example wiki repo for bitserv
1
star
71

bertiebot

A ruby implementation of BertieBot.
Ruby
1
star
72

genders

phpBB Genders MOD
PHP
1
star
73

buster-docs

Ruby
1
star