Skip to content

Instantly share code, notes, and snippets.

@aronduby aronduby/API.php
Created Nov 14, 2018

Embed
What would you like to do?
PHP/Node/Redis/Socket.IO
<?php
// require autoload
/*
* Setup Redis for PubSub for events
*/
$redis = new Predis\Client();
$pub = new Publisher($redis, 'pintourny', $subdomain);
$pub->send('event.type', $someData);
// this is the file in it's entirity, it just echos from the php publisher
var redis = require("redis"),
listener = redis.createClient(),
io = require('socket.io').listen(773,{
'close timeout': 3600, // 60 minutes to re-open a closed connection
'browser client minification': true,
'browser client etag': true,
'browser client gzip': true
});
io.sockets.on('connection', function(socket){
var domain = socket.handshake.headers.host,
sub_domain = domain.split('.').shift();
socket.join(sub_domain);
});
listener.on('message', function(channel, evt){
evt = JSON.parse(evt);
var type = evt.type,
data = evt.data,
room = evt.room;
io.to(room).emit(type, data);
});
listener.subscribe('pintourny');
<?php
class Publisher {
public $pub;
public $channel;
public $room;
public function __construct($pub, $channel, $room){
if(!method_exists($pub, 'publish'))
throw new InvalidArgumentException('Pub must be an object with a publish method');
$this->pub = $pub;
$this->channel = $channel;
$this->room = $room;
}
public function send($type, $msg){
$evt = new StdClass();
$evt->room = $this->room;
$evt->type = $type;
$evt->data = $msg;
return $this->pub->publish($this->channel, json_encode($evt));
}
}
@aronduby

This comment has been minimized.

Copy link
Owner Author

commented Nov 14, 2018

the subdomain variable is just a room to split connections up to within socket.io. This was used as part of a service where individual things would be hosted under unique subdomains

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.