VOOZH about

URL: https://deepwiki.com/hypervel/broadcasting/2.1-broadcastmanager

⇱ BroadcastManager | hypervel/broadcasting | DeepWiki


Loading...
Menu

BroadcastManager

Purpose and Scope

The BroadcastManager class is the central orchestrator and factory for the broadcasting system. It implements the factory pattern to create and manage Broadcaster instances for different backend services (Pusher, Ably, Redis, Log, Null). The manager handles driver resolution, connection caching, object pooling for network-based drivers, event queueing logic, and provides a facade API for delegating method calls to the default broadcaster.

This document covers the internal architecture of BroadcastManager, including driver instantiation, caching mechanisms, custom driver registration, and the facade pattern implementation. For information about individual broadcaster implementations, see page 3 (Broadcasting Drivers). For event broadcasting patterns, see page 4 (Event Broadcasting).

Sources: src/BroadcastManager.php36-468


Class Overview

BroadcastManager is located at src/BroadcastManager.php39 and implements the Hypervel\Broadcasting\Contracts\Factory interface. The class uses the HasPoolProxy trait to provide connection pooling capabilities for network-based broadcasters.

PropertyTypePurpose
$driversarrayCache of resolved broadcaster instances, keyed by connection name
$customCreatorsarrayRegistry of custom driver creator closures, keyed by driver name
$poolProxyClassstringFully qualified class name for pool proxy wrapper (BroadcastPoolProxy::class)
$poolablesarrayList of driver names that support connection pooling (['ably', 'pusher'])
$appContainerInterfaceDependency injection container for resolving dependencies

Sources: src/BroadcastManager.php39-69


Factory Pattern Implementation

Driver Resolution Flow

The BroadcastManager implements a multi-stage driver resolution process with caching and optional connection pooling. The resolution flow follows this sequence:


Sources: src/BroadcastManager.php220-283

Factory Methods

The manager provides dedicated factory methods for each supported driver type. These methods follow a naming convention of create{DriverName}Driver(array $config): Broadcaster.

MethodDriver TypeReturnsConfiguration Requirements
createPusherDriver()Pusher/ReverbPusherBroadcasterkey, secret, app_id, options, client_options
createReverbDriver()Reverb (alias)PusherBroadcasterSame as Pusher (delegates to createPusherDriver())
createAblyDriver()AblyAblyBroadcasterAbly SDK configuration array
createRedisDriver()RedisRedisBroadcasterconnection (Redis connection name)
createLogDriver()LogLogBroadcasterNo specific requirements
createNullDriver()NullNullBroadcasterNo specific requirements

Code Entity Mapping:


Sources: src/BroadcastManager.php294-383

Pusher/Reverb Driver Creation

The Pusher driver creation process at src/BroadcastManager.php304-338 involves:

  1. Creating a configured GuzzleClient instance with timeout and TLS settings
  2. Instantiating a Pusher object from the pusher/pusher-php-server SDK
  3. Optionally enabling PSR-3 logging if log configuration is set
  4. Wrapping the Pusher instance in a PusherBroadcaster

The createReverbDriver() method at src/BroadcastManager.php296-299 simply delegates to createPusherDriver(), as Reverb uses the Pusher protocol.

Redis Driver Creation

The Redis driver at src/BroadcastManager.php359-367 uses the hyperf/redis package's RedisFactory to obtain Redis connections and includes support for key prefixing from the database configuration.

Sources: src/BroadcastManager.php294-383

Custom Driver Registration

The extend() method at src/BroadcastManager.php426-431 allows registration of custom broadcaster implementations. Custom creators are stored in the $customCreators array and checked during the doResolve() process before built-in factory methods.

Registration Example Pattern:

BroadcastManager::extend('custom', function ($app, $config) {
 return new CustomBroadcaster($config);
});

The custom creator receives the container ($app) and driver configuration array. During resolution at src/BroadcastManager.php270-283 if a custom creator exists for the driver name, it is invoked via callCustomCreator() instead of using the built-in factory methods.

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


Driver Caching and Management

Connection Resolution

The driver(?string $name = null) method at src/BroadcastManager.php228-233 is the primary entry point for obtaining a broadcaster instance. It follows this logic:

  1. If $name is null, retrieve the default driver from configuration via getDefaultDriver()
  2. Check the $drivers cache array for an existing instance
  3. If not cached, resolve the driver via get() and cache the result
  4. Return the cached or newly created instance

The connection(?string $driver = null) method at src/BroadcastManager.php220-223 is an alias for driver(), implementing the Factory contract interface.

Sources: src/BroadcastManager.php220-233 src/BroadcastManager.php236-241

Driver Cache Management


The cache management methods include:

Sources: src/BroadcastManager.php236-263 src/BroadcastManager.php416-421 src/BroadcastManager.php454-459


Object Pooling

Poolable Drivers

The BroadcastManager uses the HasPoolProxy trait from src/BroadcastManager.php41 to provide connection pooling for network-based broadcasters. The $poolables array at src/BroadcastManager.php61 defines which drivers support pooling: ['ably', 'pusher'].

When resolving a poolable driver, the manager wraps the broadcaster instance in a BroadcastPoolProxy object (configured via $poolProxyClass at src/BroadcastManager.php56). This proxy manages a pool of broadcaster instances to optimize connection reuse for network-intensive operations.

Pool Proxy Creation Flow


The pooling logic at src/BroadcastManager.php256-262 checks if the driver name is in the $poolables array. If true, it calls createPoolProxy() (provided by HasPoolProxy trait) with:

  1. Connection name: The driver identifier
  2. Factory closure: A callback that invokes doResolve() to create actual broadcaster instances
  3. Pool configuration: The pool key from the driver's configuration array

For details on pool configuration parameters, see page 6.2 (Object Pooling & Performance).

Sources: src/BroadcastManager.php41 src/BroadcastManager.php56 src/BroadcastManager.php61 src/BroadcastManager.php248-263


Event Queue Management

Event Queueing Logic

The queue(mixed $event) method at src/BroadcastManager.php174-203 handles the logic for broadcasting events either immediately or via the queue system. This method is invoked by the event dispatcher when an event implements ShouldBroadcast.

Queue Decision Flow:


Sources: src/BroadcastManager.php174-203

ShouldBroadcastNow Handling

At src/BroadcastManager.php176-181 the manager checks if the event implements ShouldBroadcastNow or has a shouldBroadcastNow() method that returns true. If either condition is met:

  1. The event is cloned to prevent state mutation
  2. Wrapped in a BroadcastEvent job
  3. Dispatched immediately via Dispatcher::dispatchNow()
  4. The method returns early, bypassing queue logic

Sources: src/BroadcastManager.php176-181

ShouldBeUnique Handling

For events implementing ShouldBeUnique at src/BroadcastManager.php192-198 the manager:

  1. Wraps the cloned event in a UniqueBroadcastEvent instead of BroadcastEvent
  2. Invokes mustBeUniqueAndCannotAcquireLock() to attempt lock acquisition
  3. If lock acquisition fails (returns true), returns early without queueing
  4. If lock is acquired, proceeds to push the event to the queue

The lock acquisition logic at src/BroadcastManager.php208-215 uses the UniqueLock class from hypervel/bus and respects the uniqueVia() method on the event for custom cache store selection.

Sources: src/BroadcastManager.php192-215


Anonymous Broadcasting API

The BroadcastManager provides a fluent API for creating anonymous broadcasts without defining dedicated event classes. These methods instantiate AnonymousEvent objects that can be configured and broadcast on-demand.

MethodSignatureReturnsPurpose
on()on(array|Channel|string $channels)AnonymousEventBegin broadcast to arbitrary channels
private()private(string $channel)AnonymousEventBegin broadcast to a private channel
presence()presence(string $channel)AnonymousEventBegin broadcast to a presence channel
event()event(mixed $event = null)PendingBroadcastBegin broadcasting a standard event

Method Implementation Details:


Sources: src/BroadcastManager.php139-169

Anonymous Event Usage Pattern

The on() method at src/BroadcastManager.php139-142 accepts channels as an array, Channel instance, or string. It constructs an AnonymousEvent passing the manager instance and channels.

The private() and presence() methods at src/BroadcastManager.php147-158 are convenience methods that:

  1. Wrap the channel name in a PrivateChannel or PresenceChannel object
  2. Pass the channel object to on()

For detailed information on the AnonymousEvent fluent API, see page 4.2 (Anonymous Events).

Sources: src/BroadcastManager.php139-158


Route Registration

The BroadcastManager provides methods to register HTTP endpoints for channel and user authentication. These routes are required for client-side WebSocket libraries (Pusher JS, Ably, etc.) to authenticate subscriptions to protected channels.

Channel Authentication Routes

The routes(array $attributes = []) method at src/BroadcastManager.php74-95 registers the /broadcasting/auth endpoint that handles channel subscription authentication:

  1. Detects if the Hypervel\Foundation\Http\Kernel is present
  2. If present, sets default middleware to ['web'] and excludes CSRF verification via VerifyCsrfToken::class
  3. Retrieves all configured HTTP server kernels from server.kernels configuration
  4. For each kernel, registers a route accepting both GET and POST methods to /broadcasting/auth
  5. Routes to BroadcastController::authenticate method

The channelRoutes(?array $attributes = null) method at src/BroadcastManager.php121-124 is an alias for routes().

Sources: src/BroadcastManager.php74-124

User Authentication Routes

The userRoutes(?array $attributes = null) method at src/BroadcastManager.php100-114 registers the /broadcasting/user-auth endpoint for Pusher user authentication:

  1. Sets default middleware to ['web'] and excludes CSRF verification
  2. Registers route to /broadcasting/user-auth accepting GET and POST
  3. Routes to BroadcastController::authenticateUser method

This endpoint is specifically used by Pusher's user authentication feature for presence channel user identification.

Sources: src/BroadcastManager.php100-114

Socket ID Retrieval

The socket(?RequestInterface $request = null) method at src/BroadcastManager.php129-134 extracts the socket ID from the X-Socket-ID HTTP header. This socket ID is used by broadcasters to exclude the originating connection from receiving the broadcast (implementing "to others" functionality).

Sources: src/BroadcastManager.php129-134


Facade API

Dynamic Method Delegation

The BroadcastManager implements a facade pattern via the __call() magic method at src/BroadcastManager.php464-467 allowing the manager to act as a transparent proxy to the default broadcaster instance.


When any method is called on the BroadcastManager that is not defined in the class itself:

  1. PHP invokes __call($method, $parameters)
  2. The manager resolves the default driver via driver()
  3. The method call is forwarded to the broadcaster instance
  4. The result is returned to the caller

This enables the manager to expose the full Broadcaster interface without explicitly implementing every method. The @mixin \Hypervel\Broadcasting\Contracts\Broadcaster annotation at src/BroadcastManager.php37 provides IDE autocomplete support for this pattern.

Sources: src/BroadcastManager.php37 src/BroadcastManager.php464-467

Delegated Methods

Through the facade pattern, the BroadcastManager exposes all methods defined in the Broadcaster contract and base class, including:

  • auth() - Authenticate channel access
  • broadcast() - Broadcast event to channels
  • channel() - Register channel authentication callback
  • formatChannels() - Format channel names for broadcast

This delegation pattern allows the manager to be used interchangeably with a broadcaster instance throughout the application code.

Sources: src/BroadcastManager.php37 src/BroadcastManager.php464-467


Configuration Management

Configuration Retrieval

The getConfig(string $name) method at src/BroadcastManager.php388-395 retrieves driver configuration from the broadcasting.connections.{$name} configuration key. If the connection name is null or 'null', it returns a synthetic configuration array with driver set to 'null', enabling the null broadcaster without explicit configuration.

Configuration Structure Example:

broadcasting.connections.pusher => [
 'driver' => 'pusher',
 'key' => 'app-key',
 'secret' => 'app-secret',
 'app_id' => 'app-id',
 'options' => [...],
 'pool' => [...],
]

Sources: src/BroadcastManager.php388-395

Default Driver Management

MethodPurposeConfiguration Key
getDefaultDriver()Returns the default driver namebroadcasting.default
setDefaultDriver(string $name)Updates the default driver namebroadcasting.default

The default driver is used when no specific driver name is provided to driver() or connection() methods. The implementation at src/BroadcastManager.php400-411 interacts directly with the ConfigInterface to read and write the broadcasting.default configuration value.

Sources: src/BroadcastManager.php400-411


Dependency Injection Integration

The ConfigProvider class at src/ConfigProvider.php binds the BroadcastManager to the Hypervel\Broadcasting\Contracts\Factory interface in the dependency injection container:


This binding allows the factory contract to be injected into classes, with the container automatically providing a BroadcastManager instance. The manager receives the ContainerInterface via constructor injection at src/BroadcastManager.php66-69 and uses it throughout the class to resolve dependencies:

  • ConfigInterface - Configuration access
  • RequestInterface - HTTP request for socket ID extraction
  • EventDispatcherInterface - Event dispatching
  • Dispatcher - Bus dispatcher for immediate broadcasts
  • Cache - Cache factory for unique event locks
  • Queue - Queue factory for queued broadcasts
  • LoggerInterface - PSR-3 logging
  • RedisFactory - Redis connection factory
  • RouterDispatcherFactory - Route registration

The getApplication() and setApplication() methods at src/BroadcastManager.php436-449 provide access to the container for custom drivers and testing.

Sources: src/ConfigProvider.php14-16 src/BroadcastManager.php66-69 src/BroadcastManager.php436-449