VOOZH about

URL: https://deepwiki.com/hypervel/bus/5.4-dispatchesjobs-trait

⇱ DispatchesJobs Trait | hypervel/bus | DeepWiki


Loading...
Menu

DispatchesJobs Trait

Purpose and Scope

The DispatchesJobs trait provides job dispatching capability to classes that are not themselves jobs. It is designed for use in application code such as controllers, services, event listeners, and command handlers that need to dispatch jobs to the queue system but do not need to be dispatchable themselves.

This trait should not be confused with the Dispatchable trait (see 5.1), which is used on job classes to make them dispatchable. The DispatchesJobs trait is used in classes that dispatch other jobs.

Sources: src/DispatchesJobs.php1-34


Overview

The DispatchesJobs trait is defined in src/DispatchesJobs.php and contains two methods that enable any class to dispatch jobs to the command bus. These methods serve as convenient facades for the underlying dispatcher system, handling both regular job objects and closures.

Trait Structure


Sources: src/DispatchesJobs.php11-34


When to Use DispatchesJobs

The DispatchesJobs trait is appropriate for classes that need to dispatch jobs but are not themselves dispatchable. Common use cases include:

Class TypeUse CaseExample
ControllersDispatching jobs in response to HTTP requestsUser registration triggering email job
ServicesBusiness logic that delegates work to jobsOrder service dispatching payment processing
Event ListenersResponding to domain events by dispatching jobsUser created event triggering welcome email
Command HandlersCLI commands that need to queue workImport command dispatching batch processing jobs
MiddlewareRequest/response processing that triggers background workLogging middleware dispatching analytics jobs

Sources: src/DispatchesJobs.php1-34


Method Reference

dispatch() Method

The dispatch() method wraps a job in a configuration object, enabling fluent configuration before actual dispatch.

Signature:

protected function dispatch(mixed $job): mixed

Parameters:

  • $job - Either a job object or a Closure

Return Value:

  • PendingDispatch instance if $job is an object
  • PendingClosureDispatch instance if $job is a Closure

Behavior: src/DispatchesJobs.php16-21

The method checks if the provided job is a Closure. If so, it wraps it in a CallQueuedClosure (from hypervel/queue) and returns a PendingClosureDispatch. Otherwise, it returns a PendingDispatch wrapping the job object.

The returned pending object allows configuration via method chaining:


Sources: src/DispatchesJobs.php16-21


dispatchSync() Method

The dispatchSync() method immediately executes a job in the current process without queuing.

Signature:

public function dispatchSync(mixed $job): mixed

Parameters:

  • $job - The job object or closure to execute synchronously

Return Value:

  • The return value from the job's handler

Behavior: src/DispatchesJobs.php28-33

This method retrieves the Dispatcher from Hyperf's application container and calls its dispatchSync() method. Jobs dispatched this way execute immediately, bypassing the queue system entirely.


Note: As documented in the method's docblock src/DispatchesJobs.php24-26 queueable jobs (those implementing ShouldQueue) will be dispatched to the "sync" queue when using dispatchSync(), which still processes them synchronously but through the queue worker infrastructure.

Sources: src/DispatchesJobs.php28-33


Execution Flow

Asynchronous Dispatch Flow


Sources: src/DispatchesJobs.php16-21


Synchronous Dispatch Flow


Sources: src/DispatchesJobs.php28-33


Comparison with Other Dispatching Mechanisms

Trait Comparison Table

FeatureDispatchesJobsDispatchableGlobal Functions
Used InControllers, services, non-job classesJob classes themselvesAnywhere
Methodsdispatch(), dispatchSync()Static dispatch(), dispatchSync(), dispatchIf(), etc.dispatch(), dispatch_sync()
Method Visibilityprotected and publicpublic staticGlobal functions
ReturnsPendingDispatch or mixedPendingDispatch or mixedPendingDispatch or mixed
Primary Use CaseAdding dispatch capability to application classesMaking jobs self-dispatchableQuick dispatching without trait
Closure SupportYes (wraps in CallQueuedClosure)No (jobs are classes)Yes (wraps in CallQueuedClosure)

Sources: src/DispatchesJobs.php1-34


DispatchesJobs vs Dispatchable


Key Distinctions:

  1. Dispatchable Trait (5.1)

    • Applied to job classes
    • Provides static methods: Job::dispatch(), Job::dispatchSync()
    • Makes the job self-aware of how to dispatch itself
    • Example: SendEmailJob::dispatch($user)
  2. DispatchesJobs Trait (current)

    • Applied to application classes (controllers, services)
    • Provides instance methods: $this->dispatch($job), $this->dispatchSync($job)
    • Allows non-job classes to dispatch arbitrary jobs
    • Example: $this->dispatch(new SendEmailJob($user))

Sources: src/DispatchesJobs.php1-34


Implementation Details

Dependency Resolution

The dispatchSync() method uses Hyperf's dependency injection container to resolve the Dispatcher instance:

src/DispatchesJobs.php30-32

This approach ensures that the correct dispatcher instance is used, respecting any custom bindings or configurations in the application's service container.

Sources: src/DispatchesJobs.php28-33


Closure Handling

When a Closure is passed to dispatch(), it is wrapped in a CallQueuedClosure:

src/DispatchesJobs.php18-19

The CallQueuedClosure class (from hypervel/queue) serializes the closure and its bound variables so it can be queued and executed later. This is then wrapped in a PendingClosureDispatch for configuration.

Sources: src/DispatchesJobs.php16-21


Return Value Handling

The dispatch() method returns either PendingDispatch or PendingClosureDispatch, both of which support fluent configuration:

$this->dispatch($job)
 ->onConnection('redis')
 ->onQueue('high')
 ->delay(now()->addMinutes(5))
 ->afterResponse();

The actual dispatch occurs when the pending object is destructed (see 4.2 for details on the __destruct mechanism).

The dispatchSync() method returns whatever the job handler returns, making it suitable for jobs that produce results:

$result = $this->dispatchSync(new CalculateTotals($order));
// $result contains the job's return value

Sources: src/DispatchesJobs.php16-21 src/DispatchesJobs.php28-33


Usage Patterns

Pattern 1: Controller Dispatching


Pattern 2: Service Class Dispatching


Pattern 3: Event Listener Dispatching


Pattern 4: Synchronous Execution


Sources: src/DispatchesJobs.php1-34


Integration with the Dispatcher System

Architecture Context


The DispatchesJobs trait acts as a bridge between application code and the core dispatching infrastructure. It provides a clean API surface that hides the complexity of the underlying Dispatcher and queue system.

Sources: src/DispatchesJobs.php1-34


Method Visibility

Note the different visibility modifiers on the two methods:

The dispatch() method is protected to encourage its use only within the class that uses the trait, keeping dispatching logic encapsulated. The dispatchSync() method is public, allowing external callers to request synchronous execution when needed.

Sources: src/DispatchesJobs.php16 src/DispatchesJobs.php28


Summary

The DispatchesJobs trait is a simple but essential component that enables non-job classes to participate in the job dispatching system. Its two methods provide both asynchronous and synchronous dispatch capabilities, with special handling for closures and seamless integration with the PendingDispatch configuration system.

Key Takeaways:

  1. Use DispatchesJobs in controllers, services, and other application classes
  2. Use Dispatchable trait in job classes themselves (see 5.1)
  3. dispatch() returns a PendingDispatch for configuration
  4. dispatchSync() executes immediately and returns the job result
  5. Both methods support job objects and closures

Sources: src/DispatchesJobs.php1-34