VOOZH about

URL: https://deepwiki.com/hypervel/broadcasting/5.2-event-contracts

⇱ Event Contracts | hypervel/broadcasting | DeepWiki


Loading...
Menu

Event Contracts

This page documents the event-related contracts that define the interface between user application events and the broadcasting system. These contracts specify how events declare their broadcast behavior, including which channels to broadcast on, whether to broadcast immediately or via queue, and whether to enforce uniqueness constraints.

For information about the core broadcasting interfaces (Broadcaster and Factory), see Broadcasting Contracts. For implementation details about how events are processed, see Standard Broadcast Events, Anonymous Events, and Unique Events.


Contract Overview

The broadcasting system defines four event-related contracts that work together to specify event broadcasting behavior:

ContractPurposeFile Location
ShouldBroadcastDefines which channels an event broadcasts tosrc/Contracts/ShouldBroadcast.php1-17
ShouldBroadcastNowMarks events for immediate (synchronous) broadcastingsrc/Contracts/ShouldBroadcastNow.php1-9
ShouldBeUniqueMarks events for deduplication via cache lockingsrc/Contracts/ShouldBeUnique.php1-9
HasBroadcastChannelAllows models to define their own broadcast channelssrc/Contracts/HasBroadcastChannel.php1-18

Sources: src/Contracts/ShouldBroadcast.php1-17 src/Contracts/ShouldBroadcastNow.php1-9 src/Contracts/ShouldBeUnique.php1-9 src/Contracts/HasBroadcastChannel.php1-18


Contract Hierarchy and Relationships


Diagram: Event Contract Class Relationships

This class diagram shows the interface hierarchy and how concrete event classes implement the contracts. BroadcastEvent wraps events implementing ShouldBroadcast and calls their contract methods during processing.

Sources: src/Contracts/ShouldBroadcast.php7-16 src/Contracts/ShouldBroadcastNow.php7 src/Contracts/ShouldBeUnique.php7 src/Contracts/HasBroadcastChannel.php7-18 src/BroadcastEvent.php15-85


ShouldBroadcast Interface

The ShouldBroadcast interface marks an event as broadcastable. Events implementing this interface are wrapped in BroadcastEvent and queued for asynchronous broadcasting.

Required Method

The interface requires a single method:


This method returns the channels where the event should be broadcast. It can return a single Channel object or an array of Channel objects/strings.

Source: src/Contracts/ShouldBroadcast.php9-17

Optional Methods

The BroadcastEvent job handler checks for additional optional methods on the event:

MethodReturn TypePurposeCalled By
broadcastAs()stringCustom event name (defaults to class name)src/BroadcastEvent.php68-70
broadcastConnections()arrayList of broadcast connections to use (defaults to [null])src/BroadcastEvent.php72-74
broadcastWith()arrayCustom payload data (defaults to public properties)src/BroadcastEvent.php92-94

Optional Properties

These properties configure the queue job behavior when the event is wrapped in BroadcastEvent:

PropertyTypePurposeUsed By
$triesintMaximum attempts for the jobsrc/BroadcastEvent.php50
$timeoutintJob timeout in secondssrc/BroadcastEvent.php51
$backoffintSeconds to wait before retrysrc/BroadcastEvent.php52
$afterCommitboolWait for database commitsrc/BroadcastEvent.php53
$maxExceptionsintMaximum unhandled exceptionssrc/BroadcastEvent.php54
$socketstringSocket ID to exclude from broadcastsrc/BroadcastEvent.php95

Processing Flow

When an event implementing ShouldBroadcast is dispatched:

  1. Broadcasting system wraps it in BroadcastEvent (src/BroadcastEvent.php47-55)
  2. Job is queued for asynchronous processing
  3. Queue worker calls BroadcastEvent::handle() (src/BroadcastEvent.php60-85)
  4. Handler invokes broadcastOn() to get channels (src/BroadcastEvent.php62)
  5. Handler calls optional broadcastAs(), broadcastConnections(), broadcastWith() if defined
  6. Handler broadcasts to each connection via BroadcastingFactory (src/BroadcastEvent.php78-84)

Sources: src/Contracts/ShouldBroadcast.php9-17 src/BroadcastEvent.php47-106


ShouldBroadcastNow Interface

The ShouldBroadcastNow interface extends ShouldBroadcast to mark events for immediate synchronous broadcasting.

Interface Definition


This is a marker interface with no additional methods. It extends ShouldBroadcast, inheriting the broadcastOn() requirement.

Source: src/Contracts/ShouldBroadcastNow.php7-9

Behavior Differences from ShouldBroadcast

AspectShouldBroadcastShouldBroadcastNow
ExecutionAsynchronous via queueSynchronous in same process
WrapperWrapped in BroadcastEventNo wrapper, direct broadcast
TimingProcessed by queue workerImmediate before dispatch returns
Failure handlingQueue retry mechanismImmediate failure

Use Cases

Implement ShouldBroadcastNow when:

  • Queue delay is unacceptable for the use case
  • Broadcasting must complete before request finishes
  • Queue workers are unavailable
  • The event requires guaranteed immediate delivery

Trade-off: Synchronous broadcasting blocks the dispatching process and increases request latency.

Sources: src/Contracts/ShouldBroadcastNow.php1-9


ShouldBeUnique Interface

The ShouldBeUnique interface is a marker interface that enables cache-based deduplication of broadcast events.

Interface Definition


This marker interface contains no methods. When combined with ShouldBroadcast, the event is wrapped in UniqueBroadcastEvent instead of BroadcastEvent.

Source: src/Contracts/ShouldBeUnique.php1-9

Deduplication Mechanism

When an event implements both ShouldBroadcast and ShouldBeUnique:

  1. Broadcasting system wraps event in UniqueBroadcastEvent
  2. UniqueBroadcastEvent generates cache key from event class and optional uniqueId()
  3. Attempts to acquire cache lock via hypervel/cache
  4. If lock exists (duplicate event), job is discarded
  5. If lock acquired, event broadcasts and lock releases after completion

Optional Uniqueness Methods

Events can define these methods to customize deduplication:

MethodReturn TypePurposeDefault
uniqueId()stringUnique identifier for cache keyEmpty string
uniqueFor()intLock duration in secondsUntil job completes
uniqueVia()RepositoryCache driver for lock storageDefault cache

Use Cases

Implement ShouldBeUnique when:

  • Concurrent dispatches of the same event may occur
  • Duplicate broadcasts cause problems (e.g., duplicate notifications)
  • Exactly-once broadcast semantics are required
  • Preventing redundant external API calls

See page 4.3 for UniqueBroadcastEvent implementation details.

Sources: src/Contracts/ShouldBeUnique.php1-9


HasBroadcastChannel Interface

The HasBroadcastChannel interface allows model classes (e.g., User, Order) to define their own broadcast channels. This enables automatic channel generation when models are bound to channel authorization callbacks.

Interface Definition


Source: src/Contracts/HasBroadcastChannel.php7-18

Method: broadcastChannelRoute()

Returns the channel route pattern for authentication callback registration:


This method returns a template string with placeholders (e.g., 'user.{id}'). The pattern is matched against incoming authentication requests to determine which callback to invoke.

Source: src/Contracts/HasBroadcastChannel.php10-12

Method: broadcastChannel()

Returns the fully-resolved channel name for this model instance:


This method returns the actual channel name (e.g., "user.5" for user with ID 5). This is used when broadcasting events or subscribing clients to the channel.

Source: src/Contracts/HasBroadcastChannel.php14-18

Usage in Authentication

When models implement HasBroadcastChannel, they can be used in implicit model binding for channel authentication:


The Broadcaster base class uses broadcastChannelRoute() to match patterns and broadcastChannel() to resolve the actual channel name.

Sources: src/Contracts/HasBroadcastChannel.php7-18


Integration with Broadcasting System


Diagram: Event Contract Processing Flow

This flowchart shows how event contracts determine the execution path in the broadcasting system. The dispatcher checks instanceof for each contract interface and wraps the event accordingly. BroadcastEvent::handle() method calls the contract methods (broadcastOn(), broadcastAs(), etc.) and passes the data to BroadcastingFactory.

Sources: src/BroadcastEvent.php60-85 src/Contracts/ShouldBroadcast.php9-16 src/Contracts/ShouldBroadcastNow.php7 src/Contracts/ShouldBeUnique.php7


Implementation Examples

Basic Broadcast Event


Immediate Broadcast Event


Unique Broadcast Event


Model with Broadcast Channel


Event with Queue Configuration


Sources: src/BroadcastEvent.php47-106 src/Contracts/ShouldBroadcast.php9-16 src/Contracts/ShouldBroadcastNow.php7 src/Contracts/ShouldBeUnique.php7 src/Contracts/HasBroadcastChannel.php10-17


Contract Combinations

Contracts can be combined to achieve different broadcasting behaviors:

Contracts ImplementedWrapper ClassExecutionDeduplicationUse Case
ShouldBroadcastBroadcastEventQueued asyncNoStandard events
ShouldBroadcastNowNoneImmediate syncNoTime-critical events
ShouldBroadcast + ShouldBeUniqueUniqueBroadcastEventQueued asyncYesPrevent duplicate processing
ShouldBroadcastNow + ShouldBeUniqueCustom handlingImmediate syncYesCritical unique events

Note: ShouldBroadcastNow extends ShouldBroadcast, so implementing ShouldBroadcastNow automatically satisfies the ShouldBroadcast contract.

Sources: src/BroadcastEvent.php15 src/Contracts/ShouldBroadcast.php9 src/Contracts/ShouldBroadcastNow.php7 src/Contracts/ShouldBeUnique.php7


Summary

The event contracts define a clean interface between application events and the broadcasting infrastructure:

  • ShouldBroadcast: Core interface requiring broadcastOn() method to specify channels
  • ShouldBroadcastNow: Extends ShouldBroadcast for immediate broadcasting without queuing
  • ShouldBeUnique: Marker interface for cache-based deduplication
  • HasBroadcastChannel: Model interface for automatic channel generation and resolution

These contracts work together with the broader broadcasting system (documented in Standard Broadcast Events, Unique Events, and Broadcasting Contracts) to provide a flexible, type-safe broadcasting infrastructure.

Sources: src/Contracts/ShouldBroadcast.php1-17 src/Contracts/ShouldBroadcastNow.php1-9 src/Contracts/ShouldBeUnique.php1-9 src/Contracts/HasBroadcastChannel.php1-18