• Front-end development
  • AngularJS

Web sockets

Includable has the ability to send realtime messages to users through the web interface. This system is used by Includable internally to send realtime notifications.

This system consists of 2 parts: sending the message in the backend, and handling the reception of the message on the frontend.

Sending websocket message

A websocket message is always specific to a single user in a single community. It also has a type, which an be any alphanumeric string, except for the reserved type notification.

<?php

// Get user and community
$user = new User(40); // or `$user = $this->user;` if you want to target the current user
$community = 1; // or `$community = $this->site;` if you want to target the current community

// Send message
// Parameters:
// - user: User ID (int) or `User` class instance for recipient
// - community: Community ID (int) or `Community` class instance for recipient
// - type: alphanumeric string indicating message type
// - payload: string, array or object message payload (optional)
$this->socket->send($user, $community, 'message', ['body' => 'Yoyo!', 'sender' => 'Thomas']);

?>

Receiving websocket messages

First add scholica.socket to your Angular module:

var app = angular.module('ExampleApp', ['scholica.socket']);

Then listen to a channel (which is the same as the type of your message):

app.controller('ExampleController', ['$scope', '$socket', function ($scope, $socket) {
    $scope.messages = [];

    $socket.on('message', function(payload){
        $scope.messages.push(payload);
    });
}]);