VOOZH about

URL: https://deepwiki.com/hypervel/bus/5.1-dispatchable-trait

⇱ Dispatchable Trait | hypervel/bus | DeepWiki


Loading...
Menu

Dispatchable Trait

Purpose and Scope

The Dispatchable trait provides static factory methods that enable job classes to dispatch themselves. When a job class uses this trait, it gains convenient static methods like dispatch(), dispatchSync(), and withChain() that create and configure job dispatches without requiring direct instantiation or interaction with the dispatcher service.

This document covers the methods provided by the trait and their behavior. For configuring the dispatch (queue, delay, callbacks), see Configuring Job Dispatch. For details on job chaining, see Job Chaining. For the underlying Queueable properties used with Dispatchable, see Queueable Trait.


Trait Overview

The Dispatchable trait serves as a static factory interface for job classes. It allows jobs to be dispatched using an expressive, static method syntax rather than requiring manual instantiation and dispatcher injection.

Location: src/Dispatchable.php14-87

Primary Purpose: Transform new Job($args) followed by dispatcher calls into a single fluent call like Job::dispatch($args).

Trait Composition Pattern


Title: Dispatchable Trait Integration Pattern

Sources: src/Dispatchable.php14-87


Static Dispatch Methods

The trait provides six primary static methods, each serving a different dispatch pattern.

Method Summary Table

MethodReturn TypePurpose
dispatch(...$arguments)PendingDispatchCreates a pending dispatch for async/sync execution
dispatchIf($boolean, ...$arguments)PendingDispatch|FluentConditionally dispatches if condition is true
dispatchUnless($boolean, ...$arguments)PendingDispatch|FluentConditionally dispatches if condition is false
dispatchSync(...$arguments)mixedImmediately executes job in current process
dispatchAfterResponse(...$arguments)mixedDispatches after HTTP response is sent
withChain(array $chain)PendingChainCreates a job chain with this job as the first

Sources: src/Dispatchable.php19-86


Core Dispatch Method

dispatch()

The dispatch() method is the primary entry point for job dispatching. It instantiates the job with the provided arguments and wraps it in a PendingDispatch object.


Title: Dispatch Method Execution Flow

Implementation: src/Dispatchable.php19-22

Signature:


Parameters:

  • ...$arguments - Variable arguments passed to the job's constructor

Returns: A PendingDispatch instance that allows further configuration before actual dispatch

Key Behavior: The method uses new static(...$arguments) to instantiate the job class, ensuring that child classes work correctly with inheritance.

Sources: src/Dispatchable.php19-22


Conditional Dispatch Methods

dispatchIf()

Conditionally creates a PendingDispatch based on a boolean test. This method prevents the need for explicit if-statement wrapping around dispatch calls.

Implementation: src/Dispatchable.php27-40

Signature:


Parameters:

  • $boolean - A boolean value or Closure that returns a boolean
  • ...$arguments - Arguments for the job constructor

Return Behavior:

  • Returns PendingDispatch if condition evaluates to true
  • Returns Fluent (no-op object) if condition evaluates to false

Closure Parameter Pattern: When $boolean is a Closure, the job instance is passed to the closure, allowing the condition to inspect the job:


Title: dispatchIf with Closure Parameter Flow

Sources: src/Dispatchable.php27-40

dispatchUnless()

The inverse of dispatchIf(). Dispatches when the condition is false.

Implementation: src/Dispatchable.php45-58

Signature:


Logic: Identical to dispatchIf() but negates the boolean test (! value($boolean) instead of value($boolean)).

Sources: src/Dispatchable.php45-58


Synchronous Dispatch

dispatchSync()

The dispatchSync() method bypasses the pending dispatch system entirely and immediately executes the job in the current process.

Implementation: src/Dispatchable.php65-70


Title: Synchronous Dispatch Execution Path

Signature:


Key Characteristics:

  • No PendingDispatch: Does not return a PendingDispatch object; executes immediately
  • Container Resolution: Uses ApplicationContext::getContainer()->get(Dispatcher::class) to resolve the dispatcher
  • Sync Queue Override: Even if the job implements ShouldQueue, it will be dispatched to the "sync" queue, executing immediately
  • Return Value: Returns the actual result of the job handler execution

Use Cases:

  • Testing environments where async behavior is undesirable
  • Synchronous operations that must complete before proceeding
  • Debugging job execution

Sources: src/Dispatchable.php65-70


After Response Dispatch

dispatchAfterResponse()

This method provides a convenient shorthand for dispatching a job after the HTTP response has been sent to the client.

Implementation: src/Dispatchable.php75-78

Signature:


Equivalent Call Chain:


Implementation Detail: The method simply calls static::dispatch(...$arguments)->afterResponse(), demonstrating method chaining composition.

Sources: src/Dispatchable.php75-78


Chain Integration

withChain()

The withChain() method creates a PendingChain object, allowing the job to be the first job in a chain with subsequent jobs.

Implementation: src/Dispatchable.php83-86

Signature:


Parameters:

  • $chain - Array of job instances or class names to execute after this job completes successfully

Title: withChain Method Execution Flow

Key Behavior:

  • Does not instantiate the first job yet; passes the class name (static::class) to PendingChain
  • The PendingChain will instantiate the first job when dispatch() is called
  • Chain jobs are attached to the first job and execute sequentially upon success

For detailed chain mechanics, see Job Chaining.

Sources: src/Dispatchable.php83-86


Usage Patterns

Basic Dispatch


This creates a PendingDispatch that will dispatch when it destructs (see Configuring Job Dispatch).

Configured Dispatch


The PendingDispatch provides fluent configuration methods before dispatch.

Conditional Dispatch


Synchronous Execution


Chain Creation


Sources: src/Dispatchable.php14-87


Technical Implementation Details

Static Method Resolution

The trait uses new static(...$arguments) rather than new self(...$arguments). This late static binding ensures that when a child class uses the trait, the child class is instantiated, not the trait's defining class.

Example:


Sources: src/Dispatchable.php21-22

Fluent Return Object

When dispatchIf() or dispatchUnless() conditions fail, they return a Fluent object instead of null. The Fluent class (from Hyperf\Support\Fluent) provides a no-op object that safely absorbs method calls without errors.

Behavior:


This allows method chaining without conditional wrapping.

Sources: src/Dispatchable.php34-57

Container Resolution

The dispatchSync() method resolves the Dispatcher contract from the application container using ApplicationContext::getContainer()->get(Dispatcher::class).

Dependency Chain:

  1. ApplicationContext from Hyperf\Context\ApplicationContext
  2. Container's get() method resolves Dispatcher::class
  3. ConfigProvider has registered the binding (see Installation and Configuration)
  4. DispatcherFactory creates the Dispatcher instance

Sources: src/Dispatchable.php67-68


Integration with Other Traits

Dispatchable + Queueable

The Dispatchable trait creates PendingDispatch objects that read properties from the Queueable trait:


Title: Dispatchable and Queueable Trait Interaction

The Queueable trait provides properties like connection, queue, and delay that PendingDispatch reads when determining how to dispatch the job.

Sources: src/Dispatchable.php19-22

Dispatchable + Batchable

Jobs using both Dispatchable and Batchable can be dispatched as part of batches:


The Batchable trait allows the job to access its parent batch during execution. See Batchable Trait for details.

Sources: src/Dispatchable.php14-87


Code Entity Reference

Classes and Traits

EntityTypeLocation
DispatchableTraitsrc/Dispatchable.php14
PendingDispatchClassReferenced in trait, defined elsewhere
PendingChainClassReferenced in trait, defined elsewhere
DispatcherContractHypervel\Bus\Contracts\Dispatcher
FluentClassHyperf\Support\Fluent

Method Reference

MethodLinesSignature
dispatch()src/Dispatchable.php19-22public static function dispatch(mixed ...$arguments): PendingDispatch
dispatchIf()src/Dispatchable.php27-40public static function dispatchIf(bool|Closure $boolean, mixed ...$arguments): Fluent|PendingDispatch
dispatchUnless()src/Dispatchable.php45-58public static function dispatchUnless(bool|Closure $boolean, mixed ...$arguments): Fluent|PendingDispatch
dispatchSync()src/Dispatchable.php65-70public static function dispatchSync(mixed ...$arguments): mixed
dispatchAfterResponse()src/Dispatchable.php75-78public static function dispatchAfterResponse(mixed ...$arguments): mixed
withChain()src/Dispatchable.php83-86public static function withChain(array $chain): PendingChain

Dependencies

ImportPurpose
ClosureType hint for conditional dispatch closures
Hyperf\Context\ApplicationContextContainer access for dispatchSync()
Hyperf\Support\FluentNo-op return object for failed conditions
Hypervel\Bus\Contracts\DispatcherContract for dispatcher resolution
function Hyperf\Support\valueHelper to evaluate values or closures

Sources: src/Dispatchable.php1-87