VOOZH about

URL: https://deepwiki.com/hypervel/event/5.5-helper-functions

⇱ Helper Functions | hypervel/event | DeepWiki


Loading...
Menu

Helper Functions

This document describes the convenience helper functions provided by the event system for simplified event dispatching and closure queueing. These functions offer a cleaner, more expressive API for common event operations compared to directly accessing the container and dispatcher.

For information about the core event dispatching mechanism, see EventDispatcher. For details on asynchronous closure execution, see QueuedClosure.


Overview

The event system provides two global helper functions located in src/Functions.php These functions serve as facades to the core event system, reducing boilerplate code and improving readability in application code.

FunctionPurposeReturn Type
event()Dispatch an event through the event dispatcherThe dispatched event object
queueable()Wrap a closure for asynchronous executionQueuedClosure instance

Both functions are namespaced under Hypervel\Event and provide type-safe, convenient access to the event system's core functionality.

Sources: src/Functions.php1-31


Architecture: Helper Function Integration


Sources: src/Functions.php20-30 src/EventDispatcher.php31-57


The event() Helper Function

Function Signature and Behavior

The event() function provides a streamlined way to dispatch events without manually accessing the container or event dispatcher. It is defined at src/Functions.php20-25


Parameters:

  • $event (object): The event object to dispatch. Must be an object instance.

Returns: The same event object that was dispatched, allowing for method chaining or inspection of event state after listener execution.

Type Safety: The function uses a generic type parameter (@template T of object) to ensure the return type matches the input type.

Execution Flow


Sources: src/Functions.php20-25 src/EventDispatcher.php62-88

Container Resolution

The event() helper retrieves the container through ApplicationContext::getContainer() at src/Functions.php22 This requires that the application has bootstrapped the Hyperf container before any events are dispatched.

The helper then resolves the EventDispatcherInterface from the container at src/Functions.php23 The container must have bound this interface to the concrete EventDispatcher implementation, which is typically configured through ConfigProvider.

Usage Patterns

The event() helper is particularly useful in several scenarios:

Simple Event Dispatching:


Capturing Event State:


Transaction-Aware Dispatching: The helper works seamlessly with events implementing ShouldDispatchAfterCommit. The transaction-aware behavior is handled transparently by the underlying dispatcher at src/EventDispatcher.php78-85


Sources: src/Functions.php20-25 src/EventDispatcher.php62-88


The queueable() Helper Function

Function Signature and Behavior

The queueable() function wraps a closure to enable asynchronous execution through the queue system. It is defined at src/Functions.php27-30


Parameters:

  • $closure (Closure): The closure to be queued for asynchronous execution.

Returns: A QueuedClosure instance that wraps the provided closure with queue configuration capabilities.

QueuedClosure Wrapper Creation


Sources: src/Functions.php27-30 src/QueuedClosure.php15-91

Configuration Fluent API

The returned QueuedClosure object provides a fluent interface for configuring queue behavior:

MethodPurposeDefined At
onConnection(string)Set the queue connectionsrc/QueuedClosure.php49-54
delay(int)Set execution delay in secondssrc/QueuedClosure.php59-64
catch(Closure)Add error handling callbacksrc/QueuedClosure.php69-74
resolve()Create the executable closuresrc/QueuedClosure.php79-90

Integration with Event Listeners

The queueable() helper integrates with the event system's listen() method. When a QueuedClosure is passed to listen(), the dispatcher automatically resolves it at src/EventDispatcher.php129-135 or src/EventDispatcher.php137-139


Sources: src/Functions.php27-30 src/QueuedClosure.php79-90 src/EventDispatcher.php129-139

Usage Patterns

Basic Queued Listener:


Configured Queue Behavior:


Inline Registration with Type Inference: When passing a closure to listen(), the dispatcher infers the event type from the closure's first parameter. Combined with queueable(), this enables concise registration at src/EventDispatcher.php121-127:


Sources: src/Functions.php27-30 src/QueuedClosure.php15-91 src/EventDispatcher.php121-144


Helper Functions vs. Direct Usage

Comparison Table

AspectUsing HelpersDirect Usage
Event Dispatchevent($event)$container->get(EventDispatcherInterface::class)->dispatch($event)
Code LengthSingle function callMultiple method calls
DependencyGlobal functionContainer injection required
Type SafetyFull type inferenceDepends on container configuration
TestabilityRequires container setupInjectable dependency
PerformanceMinimal overhead (container lookup)Direct instance usage

When to Use Helpers

Recommended Use Cases:

  • Controllers and HTTP handlers: Quick event dispatching without injecting the dispatcher
  • Service layer code: When dependency injection is cumbersome
  • Prototyping and scripts: Rapid development without boilerplate
  • Closure-based listeners: Simplifying queue configuration syntax

When to Avoid:

  • Highly testable services: Prefer injecting EventDispatcherInterface for easier mocking
  • Performance-critical paths: Direct dispatcher usage avoids container lookups
  • Complex queue configuration: Class-based listeners with ShouldQueue interface may be clearer

Sources: src/Functions.php1-31 src/EventDispatcher.php49-57


Internal Implementation Details

Namespace and Autoloading

The helper functions are defined in the Hypervel\Event namespace at src/Functions.php5 This means they must be imported explicitly or called with the fully qualified function name:


ApplicationContext Dependency

The event() helper depends on ApplicationContext::getContainer() at src/Functions.php22 This static method provides access to the PSR-11 container. If the container has not been initialized when event() is called, it will throw an exception.

The ApplicationContext is typically initialized during the Hyperf framework bootstrap process. In testing environments, the container must be manually set up before using the helper.

EventDispatcher Resolution

The event() helper resolves the dispatcher through the EventDispatcherInterface binding at src/Functions.php23 The actual implementation is registered by the EventDispatcherFactory, which is configured in the ConfigProvider.

The factory ensures that the dispatcher is fully configured with:

  • ListenerProvider instance
  • Logger (if available)
  • Container reference
  • Queue resolver (if hypervel/queue is installed)
  • Transaction manager resolver (if hypervel/database is installed)

Sources: src/Functions.php20-25 src/EventDispatcher.php49-57


Advanced Usage: Combining Helpers

Deferred Queued Events

The helpers can be combined with the defer() method to batch queued events:


This works because event() delegates to EventDispatcher::dispatch(), which checks for deferral context at src/EventDispatcher.php64-73

Transaction-Aware Queued Closures

When combining queueable() with transaction-aware events, the queue behavior depends on listener configuration:


In this scenario:

  1. The event dispatch is deferred until transaction commit at src/EventDispatcher.php78-85
  2. When dispatched, the queued closure executes asynchronously
  3. The closure itself is not transaction-aware (only the event dispatch is)

Sources: src/Functions.php1-31 src/EventDispatcher.php64-73 src/EventDispatcher.php78-85


Performance Considerations

Container Resolution Overhead

Each call to event() performs a container lookup at src/Functions.php22-23 In performance-critical code paths with high event dispatch frequency, consider:

  1. Caching the dispatcher instance:

  1. Batch event processing: Use the defer() method to reduce immediate dispatch overhead.

QueuedClosure Serialization

The queueable() helper uses SerializableClosure for serialization at src/QueuedClosure.php83 Large closures with many captured variables increase:

  • Serialization time
  • Queue payload size
  • Deserialization time on the worker

For complex async operations, class-based listeners implementing ShouldQueue offer better performance and clarity.

Sources: src/Functions.php20-25 src/QueuedClosure.php79-90


Testing with Helper Functions

Mocking Container for Tests

When testing code that uses event(), the ApplicationContext must provide a container:


Asserting Event Dispatch

For integration testing, create a test dispatcher that records dispatched events:


Sources: src/Functions.php20-25


Summary

The helper functions provide convenient access to the event system's core functionality:

FunctionPrimary Use CaseKey Benefit
event()Dispatching eventsEliminates container boilerplate
queueable()Creating queued closuresFluent queue configuration API

Both helpers are implemented as thin wrappers that delegate to the core event system components. They reduce code verbosity while maintaining full compatibility with all event system features including transaction awareness, broadcasting, and asynchronous execution.

For production applications with strict testability requirements, consider using dependency injection to provide the EventDispatcherInterface directly. For all other scenarios, these helpers offer a more concise and expressive API.

Sources: src/Functions.php1-31 src/EventDispatcher.php49-88 src/QueuedClosure.php15-91