VOOZH about

URL: https://deepwiki.com/hypervel/broadcasting/6.4-custom-broadcasters

⇱ Custom Broadcasters | hypervel/broadcasting | DeepWiki


Loading...
Menu

Custom Broadcasters

This document provides a guide for creating custom broadcaster implementations in the hypervel/broadcasting system. It covers extending the Broadcaster base class, implementing the required contract methods, and registering custom drivers with the BroadcastManager. For information about the built-in broadcasters (Pusher, Ably, Redis, Log, Null), see Broadcasting Drivers. For details on channel authentication and authorization mechanics, see Authentication & Authorization.

Overview

Custom broadcasters allow developers to integrate additional real-time messaging backends beyond the built-in drivers. The system provides a structured approach for creating custom implementations through:

  1. Implementing the Broadcaster contract interface
  2. Extending the abstract Broadcaster base class for authentication support
  3. Registering the custom driver via BroadcastManager::extend()
  4. Configuring the custom driver in the broadcasting configuration

Sources: src/BroadcastManager.php36-468 src/Broadcasters/Broadcaster.php1-304 src/Contracts/Broadcaster.php1-26

Custom Broadcaster Registration Flow

The following diagram illustrates how custom broadcasters are registered and resolved by the BroadcastManager:


Sources: src/BroadcastManager.php426-431 src/BroadcastManager.php270-283 src/BroadcastManager.php288-291

The Broadcaster Contract

All broadcaster implementations must satisfy the Broadcaster contract interface, which defines three core methods:

MethodParametersReturn TypePurpose
auth()RequestInterface $requestmixedAuthenticate incoming channel subscription requests
validAuthenticationResponse()RequestInterface $request, mixed $resultmixedFormat the authentication response for the specific driver
broadcast()array $channels, string $event, array $payloadvoidPublish events to the specified channels

The contract is defined at src/Contracts/Broadcaster.php9-25 and represents the minimum interface that any broadcaster must implement.

Sources: src/Contracts/Broadcaster.php1-26

Extending the Broadcaster Base Class

The abstract Broadcaster base class at src/Broadcasters/Broadcaster.php23-304 provides channel authentication infrastructure that custom implementations should extend. This base class handles:

Channel Authentication Registry

The base class maintains static registries for channel patterns and authentication callbacks:

  • $channels - Maps channel patterns to authentication callbacks
  • $channelOptions - Stores configuration options (guards, etc.) per channel pattern

Sources: src/Broadcasters/Broadcaster.php38-43

User Resolution

The base class provides methods for resolving authenticated users:

  • retrieveUser(string $channel) - Retrieves the authenticated user for the given channel, respecting guard configuration
  • resolveAuthenticatedUser(RequestInterface $request) - Resolves user payload for user authentication endpoints
  • resolveAuthenticatedUserUsing(Closure $callback) - Registers a custom user resolution callback

Sources: src/Broadcasters/Broadcaster.php50-67 src/Broadcasters/Broadcaster.php243-262

Channel Pattern Matching

The base class implements pattern matching and parameter extraction:

  • verifyUserCanAccessChannel() - Orchestrates the authentication flow
  • channelNameMatchesPattern() - Checks if a channel name matches a registered pattern
  • extractAuthParameters() - Extracts parameters from channel patterns (e.g., private-order.{orderId})
  • resolveImplicitBindingIfPossible() - Performs implicit model binding for route-bindable parameters

Sources: src/Broadcasters/Broadcaster.php92-114 src/Broadcasters/Broadcaster.php119-128 src/Broadcasters/Broadcaster.php189-206

Channel Registration

The channel() method allows registering authentication callbacks for channel patterns:

channel(HasBroadcastChannel|string $channel, callable|string $callback, array $options = []): static

This method supports:

  • String channel patterns with placeholders (e.g., private-user.{id})
  • Model classes implementing HasBroadcastChannel
  • Callback functions or class-based handlers with a join() method

Sources: src/Broadcasters/Broadcaster.php72-85

Implementing Required Methods

Custom broadcasters must implement the three contract methods. The following table shows typical responsibilities for each method based on built-in implementations:

Method Implementation Requirements

MethodTypical ImplementationReference Implementations
auth()Parse request parameters (channel name, socket ID), invoke verifyUserCanAccessChannel(), return driver-specific response formatPusherBroadcaster49-61 AblyBroadcaster49-61 RedisBroadcaster56-68
validAuthenticationResponse()Format authentication result for the driver's protocol (signatures, tokens, JSON structure)PusherBroadcaster69-108 AblyBroadcaster69-88 RedisBroadcaster76-88
broadcast()Format and publish messages to channels via the backend service (API calls, pub/sub, etc.)PusherBroadcaster116-125 AblyBroadcaster96-104 RedisBroadcaster96-116

Sources: src/Broadcasters/PusherBroadcaster.php49-125 src/Broadcasters/AblyBroadcaster.php49-104 src/Broadcasters/RedisBroadcaster.php56-116

Custom Broadcaster Architecture

The following diagram shows the class hierarchy and method requirements for a custom broadcaster:


Sources: src/Contracts/Broadcaster.php9-25 src/Broadcasters/Broadcaster.php23-304

Registering Custom Broadcasters

Custom broadcasters are registered using the BroadcastManager::extend() method. This method accepts two parameters:

  1. Driver name - String identifier for the custom driver (used in configuration)
  2. Creator callback - Closure that receives ContainerInterface and configuration array, returns broadcaster instance

Registration Pattern

The typical registration occurs in a service provider or bootstrap file:

$broadcastManager->extend('custom-driver', function (ContainerInterface $app, array $config) {
 return new CustomBroadcaster($app, new ServiceClient($config));
});

The extend() method stores the callback in the customCreators array at src/BroadcastManager.php51 and returns the manager instance for method chaining.

Sources: src/BroadcastManager.php424-431

Custom Driver Resolution Flow

The following diagram illustrates how custom drivers are resolved when an application broadcasts events:


Sources: src/BroadcastManager.php228-233 src/BroadcastManager.php238-241 src/BroadcastManager.php248-263 src/BroadcastManager.php270-283 src/BroadcastManager.php288-291

Configuration Structure

Custom broadcasters require configuration entries in the broadcasting.connections array:

Configuration KeyPurposeExample
driverDriver name matching the registered custom driver'custom-driver'
keyAPI key or authentication credential'api-key-123'
secretSecret key for signing requests'secret-xyz'
endpointService endpoint URL'https://api.service.com'
optionsDriver-specific options array['timeout' => 30]
poolObject pool configuration (if poolable)['min_connections' => 1]

The configuration is retrieved by BroadcastManager::getConfig() at src/BroadcastManager.php388-395 and passed to the custom creator closure.

Sources: src/BroadcastManager.php388-395

Object Pooling Support

Custom broadcasters can optionally support connection pooling by declaring the driver as poolable. To enable pooling:

  1. Add the driver name to BroadcastManager::$poolables array at src/BroadcastManager.php61
  2. Provide a pool configuration array with pooling parameters
  3. The broadcaster will be automatically wrapped in a BroadcastPoolProxy instance

The pooling mechanism is controlled by the HasPoolProxy trait at src/BroadcastManager.php41 and wraps the broadcaster using createPoolProxy() when the driver is in the poolables list.

Sources: src/BroadcastManager.php41 src/BroadcastManager.php61 src/BroadcastManager.php256-262

Integration with Authentication System

Custom broadcasters inherit the authentication infrastructure from the Broadcaster base class. The authentication flow:


Custom broadcasters should:

  1. Extract channel name and socket ID from the request in auth()
  2. Invoke verifyUserCanAccessChannel() to perform authentication
  3. Format the authentication result in validAuthenticationResponse() according to the driver's protocol

Sources: src/BroadcastController.php1-100 src/Broadcasters/Broadcaster.php92-114

Example Custom Broadcaster Structure

A minimal custom broadcaster implementation structure:

namespace App\Broadcasting;

use Hyperf\HttpServer\Contract\RequestInterface;
use Hypervel\Broadcasting\Broadcasters\Broadcaster;
use Psr\Container\ContainerInterface;

class CustomBroadcaster extends Broadcaster
{
 public function __construct(
 ContainerInterface $container,
 protected CustomServiceClient $client
 ) {
 $this->container = $container;
 }

 public function auth(RequestInterface $request): mixed
 {
 // 1. Extract parameters
 $channelName = $request->input('channel_name');
 $socketId = $request->input('socket_id');
 
 // 2. Verify access (inherited from base class)
 return $this->verifyUserCanAccessChannel($request, $channelName);
 }

 public function validAuthenticationResponse(RequestInterface $request, mixed $result): mixed
 {
 // Format response for custom driver protocol
 // Return signatures, tokens, or driver-specific structure
 }

 public function broadcast(array $channels, string $event, array $payload = []): void
 {
 // Format and publish message via custom service
 $this->client->publish($channels, $event, $payload);
 }
}

Registration in service provider:

$manager = $this->app->get(BroadcastManager::class);
$manager->extend('custom', function ($app, $config) {
 $client = new CustomServiceClient($config);
 return new CustomBroadcaster($app, $client);
});

Sources: src/Broadcasters/Broadcaster.php23-304 src/BroadcastManager.php426-431