VOOZH about

URL: https://deepwiki.com/hypervel/bus/8.2-events

⇱ Events | hypervel/bus | DeepWiki


Loading...
Menu

Events

Purpose and Scope

This page documents the event system within the hypervel/bus package, specifically the BatchDispatched event that is fired during batch lifecycle operations. Events provide a mechanism for external code to observe and react to batch operations without directly coupling to the batch processing logic.

For information about batch lifecycle callbacks (before, progress, then, catch, finally), see Batch Callbacks and Lifecycle. For general batch processing concepts, see Batch Processing.

Overview

The hypervel/bus package integrates with Hyperf's event system to broadcast notifications about batch operations. This allows applications to implement cross-cutting concerns such as logging, monitoring, notifications, or custom business logic that should execute when batches are created and dispatched.

The event system is distinct from the batch callback mechanism:

FeatureEventsCallbacks
Attachment PointRegistered globally via Hyperf's event dispatcherConfigured per-batch via PendingBatch methods
ScopeApplication-wide observersBatch-specific handlers
Use CaseCross-cutting concerns (logging, metrics, notifications)Batch-specific completion/error handling
ExecutionAll registered listeners executeOnly the callbacks configured for that specific batch

Sources: src/Events/BatchDispatched.php1-15

BatchDispatched Event

Event Structure

The BatchDispatched event is a simple data transfer object that carries a reference to the dispatched batch. The event class is defined in the Hypervel\Bus\Events namespace.


Event Class Structure Diagram: Shows the BatchDispatched event class and its relationship to the Batch object it carries.

The event provides read-only access to the batch through its public batch property:

  • batch (Hypervel\Bus\Batch): The batch instance that was dispatched. This provides access to all batch properties and methods, including:
    • Batch identification (id, name)
    • Job counts (totalJobs, pendingJobs, failedJobs)
    • Status methods (finished(), cancelled(), hasFailures())
    • Configuration options

Sources: src/Events/BatchDispatched.php9-14

Event Properties

PropertyTypeDescription
batchHypervel\Bus\BatchThe batch object that has been dispatched, containing all batch metadata and state

The Batch object referenced by the event provides comprehensive information about the batch operation, allowing listeners to access batch configuration, track job counts, and query batch status.

Sources: src/Events/BatchDispatched.php11-13

When the Event is Fired

The BatchDispatched event is fired when a batch is dispatched to the queue system. This occurs during the batch dispatch lifecycle, after the batch has been created and configured but before individual jobs within the batch begin executing.


Batch Dispatch Sequence: Shows when the BatchDispatched event is fired in relation to other batch lifecycle operations.

The event dispatch occurs at a specific point in the batch lifecycle:

  1. After batch creation: The Batch object has been instantiated by BatchFactory
  2. After persistence: The batch has been stored in the BatchRepository
  3. Before callback execution: Prior to executing any before callbacks configured on the batch
  4. Before job dispatch: Before individual jobs are pushed to the queue

This timing ensures that listeners receive the event with a fully-formed, persisted batch object that has a stable ID and can be referenced safely.

Sources: src/Events/BatchDispatched.php1-15

Listening to Batch Events

Applications can listen to the BatchDispatched event by registering listeners through Hyperf's event system. Hyperf provides multiple mechanisms for event listener registration.

Listener Implementation Methods


Listener Registration Architecture: Shows the three primary methods for registering event listeners in Hyperf and how they connect to the event dispatcher.

Method 1: Annotation-Based Listener

Create a listener class with the @Listener annotation:


Method 2: Configuration Array Registration

Register listeners in config/autoload/listeners.php:


Method 3: Manual Registration

Register listeners programmatically using the EventDispatcher:


Sources: src/Events/BatchDispatched.php1-15

Common Use Cases

The BatchDispatched event enables several practical monitoring and notification scenarios:

Logging and Auditing

Track when batches are created and dispatched for audit trails:


Metrics Collection

Send batch metrics to monitoring systems:


Notifications

Notify relevant parties when large batches are initiated:


Integration with External Systems

Synchronize batch information with external tracking systems:


Sources: src/Events/BatchDispatched.php1-15

Event vs Callback Comparison

Understanding the distinction between events and callbacks is essential for proper system design:


Events vs Callbacks Architecture: Illustrates the different execution points and audiences for events versus callbacks in the batch lifecycle.

Key Differences

AspectEventsCallbacks
ConfigurationGlobal, via Hyperf's event systemPer-batch, via PendingBatch methods
Execution TimingImmediately when event is firedAt specific lifecycle points
Data AccessRead-only access to Batch objectFull access to Batch object and can modify state
Failure HandlingListener exceptions don't affect batchCallback exceptions can trigger catch/finally callbacks
Use CaseObservability, cross-cutting concernsBusiness logic, completion handling
SerializationNot serializedSerialized with the batch

When to Use Events

Choose events when:

  • Multiple independent components need to react to batch dispatch
  • The logic is cross-cutting (logging, metrics, notifications)
  • You want loose coupling between batch operations and observers
  • The reaction doesn't affect batch execution

When to Use Callbacks

Choose callbacks when:

  • The logic is specific to a particular batch operation
  • You need to execute code at precise lifecycle points (progress, completion, failure)
  • The handler should be co-located with batch configuration
  • The logic is part of the business process, not just observation

Sources: src/Events/BatchDispatched.php1-15

Event Payload Details

The BatchDispatched event provides access to the complete Batch object, which exposes:

Batch Identification

  • id: Unique identifier for the batch (typically a UUID)
  • name: Human-readable name assigned during batch creation

Job Counts

  • totalJobs: Total number of jobs in the batch
  • pendingJobs: Number of jobs not yet processed
  • failedJobs: Number of jobs that have failed
  • processedJobs(): Method returning count of completed jobs

Status Methods

  • finished(): Returns true if all jobs have completed (successfully or failed)
  • cancelled(): Returns true if the batch has been cancelled
  • hasFailures(): Returns true if any jobs have failed
  • allowsFailures(): Returns true if the batch is configured to continue despite failures

Configuration Access

  • options: Array of batch configuration options including queue, connection, and callback definitions

This comprehensive access allows event listeners to make informed decisions based on batch characteristics and current state.

Sources: src/Events/BatchDispatched.php11-13

Integration with Hyperf's Event System

The hypervel/bus event system fully integrates with Hyperf's event dispatcher, which means:

Event Propagation

Events are dispatched through Hyperf's Psr\EventDispatcher\EventDispatcherInterface, following PSR-14 standards. All registered listeners for BatchDispatched will be notified in registration order.

Asynchronous Listening

Listeners can be configured as asynchronous using Hyperf's async listener capabilities, allowing heavy processing to occur without blocking batch dispatch.

Event Priorities

Hyperf supports listener priorities. If multiple listeners need to execute in a specific order, use the priority property in the @Listener annotation:


Stoppable Events

While BatchDispatched does not implement Psr\EventDispatcher\StoppableEventInterface, the Hyperf event system supports stoppable events. If needed, custom event classes can implement this interface to allow listeners to prevent subsequent listener execution.

Sources: src/Events/BatchDispatched.php1-15

Summary

The hypervel/bus package provides a minimal but effective event system centered on the BatchDispatched event. This event fires when batches are dispatched to the queue system, carrying a complete Batch object that provides access to all batch metadata and state.

Applications can leverage this event for:

  • Monitoring and observability
  • Audit logging
  • Metrics collection
  • External system integration
  • Notifications

The event system complements but does not replace the batch callback system documented in Batch Callbacks and Lifecycle. Events are for global, cross-cutting concerns, while callbacks are for batch-specific business logic.

Sources: src/Events/BatchDispatched.php1-15