# Channels

Channels are a way to send messages to a group of users. For example, you can send a message to all users in a conversation or to all users in a forum. Or you can send a message to a specific user.

There are three types of channels:

  • Public: access is not limited in any way, all users can connect.
  • Presence: access can be limited. Makes possible to get a list of users present in the channel.
  • Private: access to the channel requires a signature, which is issued if the user has permission to access the channel.

# How to add a channel?

Create your own channel class in the YourAddon/Broadcasting directory. It must extends one of the base classes:

  • BS\XFWebSockets\Broadcasting\Channel - for public channels.
  • BS\XFWebSockets\Broadcasting\PrivateChannel - for private channels.
  • BS\XFWebSockets\Broadcasting\PresenceChannel - for presence channels.

Create a new listener for the broadcast_channels event:

use YourAddons\Broadcasting\ThreadChannel;

public static function broadcastChannels(array &$channels)
{
    $channels['Thread.{id}'] = ThreadChannel::class;
}

# How to authorize user access to a channel?

Add a join method to your channel that returns a boolean:

namespace YourAddon\Broadcasting;

use BS\XFWebSockets\Broadcasting\PresenceChannel;

class ThreadChannel extends PresenceChannel
{
    public function join(\XF\Entity\User $visitor, $id): bool
    {
        $thread = \XF::em()->find('XF:Thread', $id);
        if (!$thread) {
            return false;
        }
        
        return \XF::asVisitor($visitor, function () use ($thread) {
            return $thread->canView();
        });
    }
}