VOOZH about

URL: https://deepwiki.com/hypervel/broadcasting/4.2-anonymous-events

⇱ Anonymous Events | hypervel/broadcasting | DeepWiki


Loading...
Menu

Anonymous Events

Purpose and Scope

This document covers the AnonymousEvent class, which enables ad-hoc event broadcasting without creating formal event classes. Anonymous events provide a fluent API for quickly dispatching broadcasts when defining a dedicated event class is unnecessary or impractical.

For information about standard broadcast events that implement ShouldBroadcast, see Standard Broadcast Events. For the event contracts and interfaces, see Event Contracts.


Overview

The AnonymousEvent class allows applications to broadcast messages directly without defining event classes. It implements the ShouldBroadcast contract and provides a chainable API for configuring all broadcasting parameters inline.

Key Features:

  • Fluent API for configuring channels, payloads, and broadcasting behavior
  • Support for all channel types (public, private, presence, encrypted)
  • Connection selection and socket exclusion
  • Immediate or queued broadcasting
  • No formal event class definition required

Sources: src/AnonymousEvent.php1-154


Class Structure

Inheritance and Traits

The AnonymousEvent class uses multiple traits to compose its functionality:

TraitPurposeSource
DispatchableProvides static dispatch() method for event creationLine 16
InteractsWithBroadcastingEnables connection selection and channel configurationLine 17
InteractsWithSocketsSupports socket-based user exclusion (toOthers)Line 18

Sources: src/AnonymousEvent.php14-18

Dependencies


Diagram: AnonymousEvent Class Dependencies

Sources: src/AnonymousEvent.php14-48


Creating Anonymous Events

Constructor Requirements

The AnonymousEvent constructor requires two parameters:

ParameterTypeDescription
$broadcastManagerBroadcastManagerManager instance for broadcasting execution
$channelsarray|Channel|stringTarget channel(s) for the broadcast

The constructor normalizes the channels parameter into an array using Arr::wrap().

Sources: src/AnonymousEvent.php48-51

Internal State

The class maintains the following protected properties:

PropertyTypeDefaultDescription
$connection?stringnullBroadcaster connection to use
$name?stringnullEvent name for broadcast
$payloadarray[]Data to broadcast
$includeCurrentUserbooltrueWhether to include current user in broadcast
$shouldBroadcastNowboolfalseWhether to broadcast synchronously
$channelsarray(required)Channels to broadcast on

Sources: src/AnonymousEvent.php20-50


Fluent Configuration API

Configuration Methods


Diagram: AnonymousEvent Fluent API Flow

Sources: src/AnonymousEvent.php53-117

Method Details

via(string $connection): static

Sets the broadcaster connection to use for this event. This allows selecting a specific driver configuration from broadcasting.php.

Sources: src/AnonymousEvent.php56-61

as(string $name): static

Sets the event name that will be broadcast. If not set, the class basename is used as the event name.

Sources: src/AnonymousEvent.php66-71

with(array|Arrayable $payload): static

Sets the payload data to broadcast. Accepts either:

  • Plain array
  • Instance implementing Arrayable interface

The method recursively converts Arrayable objects to arrays, ensuring all payload data is serializable.

Sources: src/AnonymousEvent.php76-85

toOthers(): static

Excludes the current user from receiving the broadcast. Sets $includeCurrentUser to false, which is checked during the broadcast execution.

Sources: src/AnonymousEvent.php90-95


Broadcasting Execution

Broadcasting Flow


Diagram: Anonymous Event Broadcasting Sequence

Sources: src/AnonymousEvent.php100-117

send(): void

Queues the event for asynchronous broadcasting:

  1. Creates a PendingBroadcast wrapper via $broadcastManager->event($this)
  2. Applies the specified connection using via($connection)
  3. Applies socket exclusion if toOthers() was called
  4. Returns without waiting for broadcast completion

Sources: src/AnonymousEvent.php110-117

sendNow(): void

Broadcasts the event immediately without queuing:

  1. Sets $shouldBroadcastNow to true
  2. Calls send() method
  3. The shouldBroadcastNow() method returns true, signaling immediate execution

Sources: src/AnonymousEvent.php100-105


ShouldBroadcast Implementation

The AnonymousEvent class implements all required methods of the ShouldBroadcast contract:

Method Implementations

MethodReturn TypeDescriptionSource
broadcastAs()stringReturns event name or class basenamesrc/AnonymousEvent.php122-125
broadcastWith()arrayReturns configured payload datasrc/AnonymousEvent.php132-135
broadcastOn()arrayReturns array of channel objects/stringssrc/AnonymousEvent.php142-145
shouldBroadcastNow()boolReturns synchronous broadcast flagsrc/AnonymousEvent.php150-153

Event Name Resolution


Diagram: broadcastAs() Name Resolution Logic

If no custom name is set via as(), the method falls back to the class basename, which for anonymous events is "AnonymousEvent".

Sources: src/AnonymousEvent.php122-125


Integration with BroadcastManager

Manager Interaction

The AnonymousEvent integrates with BroadcastManager through the following interaction pattern:


Diagram: AnonymousEvent and BroadcastManager Integration

The send() method delegates to the BroadcastManager:

  1. Calls $this->broadcastManager->event($this) to create a PendingBroadcast
  2. Configures the pending broadcast with connection and exclusion settings
  3. Allows BroadcastManager to handle queue/immediate broadcast logic

Sources: src/AnonymousEvent.php110-117


Usage Patterns

Typical Usage Example

Anonymous events follow this general pattern:

  1. Instantiate with BroadcastManager and target channels
  2. Chain configuration methods (via, as, with, toOthers)
  3. Execute with send() or sendNow()

Channel Configuration

The constructor accepts flexible channel formats:

Input TypeExampleResult
String"order-updates"["order-updates"]
Channel objectnew Channel("alerts")[Channel instance]
Array of strings["news", "alerts"]["news", "alerts"]
Array of Channels[new Channel("a"), new Channel("b")][Channel instances]

All formats are normalized to arrays by Arr::wrap().

Sources: src/AnonymousEvent.php48-51

Payload Serialization

The with() method handles complex payload structures:

  • Direct arrays pass through unchanged
  • Arrayable objects are converted to arrays
  • Nested Arrayable objects within collections are recursively converted
  • Uses collect() helper for array mapping when needed

This ensures all data is serializable for queue storage and JSON transmission.

Sources: src/AnonymousEvent.php76-85


Comparison with Standard Events

AspectAnonymousEventStandard Events (4.1)
Class definitionNo class file neededDedicated event class required
ConfigurationFluent API at runtimeProperties/methods in class
ReusabilitySingle-use, inlineReusable across application
Type safetyRuntime configurationCompile-time type checking
IDE supportLimited autocompletionFull IDE assistance
Use caseQuick, one-off broadcastsStructured, recurring events

Anonymous events are ideal for prototyping, testing, or scenarios where creating a formal event class would be unnecessarily verbose. Standard events provide better structure for production systems with repeated broadcasting patterns.

Sources: src/AnonymousEvent.php1-154