Elephant.io provides a socket.io client fully written in PHP that should be usable everywhere in your project.
It is a light and easy to use library that aims to bring some real-time functionality to a PHP application through socket.io and websockets for actions that could not be done in full javascript, such as:
For elephant.io magic to operate, the following dependencies must be fulfilled :
The classic connection. It will allow you to connect to your socket.io instance and then emits something to it. It will then disconnect at the end of the script. We recommend using this for the time being.
use ElephantIO\Client as Elephant;
$elephant = new Elephant('http://localhost:8000', 'socket.io', 1, false, true, true);
$elephant->init();
$elephant->send(
ElephantIOClient::TYPE_EVENT,
null,
null,
json_encode(array('name' => 'foo', 'args' => 'bar'))
);
$elephant->close();
echo 'tryin to send `bar` to the event `foo`';
var io = require('socket.io').listen(8000);
io.sockets.on('connection', function (socket) {
console.log('user connected!');
socket.on('foo', function (data) {
console.log('here we are in action event and data is: ' + data);
});
});
For a persistent connection, here is an example of how to initiate the connection and emit an Hello World message. Once the message is sent, the connection will be kept with the socket.io server. It is still not recommended to use this at the time, as this feature is being at an early stage of development.
require('ElephantIOClient.class.php');
$elephant = new ElephantIOClient('http://localhost:1337');
$elephant->init();
$elephant->send(ElephantIOClient::TYPE_MESSAGE, null, null, 'Hello World!');
$elephant->keepAlive();
init($keepalive = false)
Init will initialize the connection to socket.io
Parameters:
$keepalive - boolean - If true, the init launch keepAlive() at the end of the method
keepAlive()
keepAlive make a persistent connection with socket.io by sending back heartbeats.
read()
Read retrieve the latest incoming data.
send($type, $id = null, $endpoint = null, $message = null)
Send allow you to send message to socket.io.
Parameters:
$type - integer - the message type, you can use constants for more ease. Available constants:
$client->init();
$client->send(Client::TYPE_MESSAGE, null, null, ‘Hello World!’);
$client->stdout(‘debug’, ‘connected!’);
More to come... Feel free to submit your features requests on our Github issues page !