VOOZH about

URL: https://deepwiki.com/hypervel/bus/7.3-nested-batches-and-chaining

⇱ Nested Batches and Chaining | hypervel/bus | DeepWiki


Loading...
Menu

Nested Batches and Chaining

Purpose and Scope

This document explains how batches can be nested within job chains and how batches can themselves be part of larger job chains. The ChainedBatch class enables batches to participate in sequential job execution patterns by wrapping PendingBatch instances into queueable jobs that can be chained with other jobs.

For information about creating and configuring batches, see Creating and Managing Batches. For information about batch lifecycle and callbacks, see Batch Callbacks and Lifecycle. For information about job chaining in general, see Job Chaining.

Sources: src/ChainedBatch.php1-131


ChainedBatch Overview

The ChainedBatch class is a special job type that wraps a PendingBatch instance, making it executable within a job chain. This allows batch operations to be sequenced with other jobs in a chain.

Class Structure

ChainedBatch implements ShouldQueue and uses several key traits:

TraitPurpose
BatchableAllows the ChainedBatch itself to be part of a parent batch
DispatchableProvides static dispatch methods
InteractsWithQueueEnables queue interaction capabilities
QueueableProvides queue configuration properties

The class stores three main properties:

  • jobs (Collection): The collection of jobs to be batched
  • name (string): The batch name
  • options (array): The batch configuration options

Sources: src/ChainedBatch.php14-45

ChainedBatch Class Diagram


Sources: src/ChainedBatch.php14-45


Recursive Batch Preparation

The prepareNestedBatches() static method recursively processes job collections to identify and wrap any PendingBatch instances within the collection.

Method Signature

public static function prepareNestedBatches(Collection $jobs): Collection

Processing Logic

The method maps over the job collection and handles four distinct cases:

CaseDetectionAction
Arrayis_array($job)Recursively process the array as a collection
Collection$job instanceof CollectionRecursively process the collection
PendingBatch$job instanceof PendingBatchWrap in a new ChainedBatch
OtherdefaultReturn as-is

This recursive approach ensures that deeply nested batch structures are properly converted, regardless of nesting depth.

Sources: src/ChainedBatch.php47-58

Recursive Processing Flow


Sources: src/ChainedBatch.php47-58


Execution Flow

When a ChainedBatch job executes, it follows a specific flow to convert back to a PendingBatch and dispatch it.

Handle Method

The handle() method is the entry point when the job executes:

public function handle(): void
{
 $this->attachRemainderOfChainToEndOfBatch(
 $this->toPendingBatch()
 )->dispatch();
}

This method:

  1. Converts the ChainedBatch to a PendingBatch via toPendingBatch()
  2. Attaches any remaining chain jobs via attachRemainderOfChainToEndOfBatch()
  3. Dispatches the resulting batch

Sources: src/ChainedBatch.php60-68

Converting to PendingBatch

The toPendingBatch() method reconstructs a PendingBatch from the stored properties:

StepAction
1Retrieve Dispatcher from container
2Call batch($this->jobs) to create new PendingBatch
3Restore name and options
4Apply queue and connection if set
5Register chain catch callbacks as batch catch callbacks

The catch callback registration includes a check for allowsFailures() to ensure that chain-level catch callbacks only fire when the batch doesn't allow failures.

Sources: src/ChainedBatch.php70-99

PendingBatch Reconstruction Flow


Sources: src/ChainedBatch.php70-99


Chain Integration

The ChainedBatch class provides sophisticated integration with job chains through the attachRemainderOfChainToEndOfBatch() method.

Chain Continuation Mechanism

When a ChainedBatch has remaining jobs in its chain (stored in $this->chained), these jobs must be dispatched after the batch completes. The implementation:

  1. Checks for chained jobs: if (! empty($this->chained))
  2. Retrieves next job: Unserializes the first job from the chain
  3. Transfers chain metadata: Copies chained, chainConnection, chainQueue, and chainCatchCallbacks to the next job
  4. Registers finally callback: Adds a callback that dispatches the next job when the batch finishes

Finally Callback Logic

The finally callback attached to the batch ensures chain continuation:

$batch->finally(function (Batch $batch) use ($next) {
 if (! $batch->cancelled()) {
 ApplicationContext::getContainer()
 ->get(Dispatcher::class)
 ->dispatch($next);
 }
});

This callback only dispatches the next job if the batch was not cancelled, preventing chain continuation when batch execution is stopped.

Sources: src/ChainedBatch.php101-130

Chain Attachment Flow


Sources: src/ChainedBatch.php101-130


Technical Architecture

Complete Nested Batch Execution Lifecycle

The following diagram shows the complete flow from creating a chained batch through execution and chain continuation:


Sources: src/ChainedBatch.php1-131 src/PendingBatch.php240-267

Nested Batch Data Structure

When batches are nested, the data structure can become deeply hierarchical:


In this structure:

  • The main chain contains regular jobs and a ChainedBatch
  • ChainedBatch 1 contains jobs and another nested ChainedBatch
  • ChainedBatch 2 contains additional jobs
  • The prepareNestedBatches() method recursively processes this structure

Sources: src/ChainedBatch.php47-58


Key Behaviors and Considerations

Catch Callback Propagation

When chain catch callbacks are registered on a ChainedBatch, they are propagated to the PendingBatch with conditional logic:

$batch->catch(function (Batch $batch, ?Throwable $exception) use ($callback) {
 if (! $batch->allowsFailures()) {
 $callback($exception);
 }
});

This ensures that chain-level error handlers only fire when the batch itself does not allow failures. If allowFailures() is true, batch jobs can fail without triggering chain failure.

Sources: src/ChainedBatch.php90-96

Connection and Queue Inheritance

Queue connection and queue name follow a specific inheritance pattern:

PropertySource Priority
Connection1. ChainedBatch.connection
2. ChainedBatch.chainConnection
Queue1. ChainedBatch.queue
2. ChainedBatch.chainQueue

This allows each job in a chain to override connection/queue settings while defaulting to chain-level settings.

Sources: src/ChainedBatch.php82-88 src/ChainedBatch.php111-112

Batch Cancellation and Chain Termination

The finally callback includes a cancellation check:

if (! $batch->cancelled()) {
 // dispatch next job
}

This prevents chain continuation when a batch is explicitly cancelled, ensuring that batch cancellation stops the entire chain at that point.

Sources: src/ChainedBatch.php119-123


Integration Points

Constructor Integration

The ChainedBatch constructor accepts a PendingBatch and immediately processes nested batches:

public function __construct(PendingBatch $batch)
{
 $this->jobs = static::prepareNestedBatches($batch->jobs);
 $this->name = $batch->name;
 $this->options = $batch->options;
}

This ensures that all nested batches are wrapped at creation time.

Sources: src/ChainedBatch.php39-45

Dispatcher Integration

The ChainedBatch uses the Dispatcher contract from the container to:

  1. Create new PendingBatch instances via batch()
  2. Dispatch continuation jobs via dispatch()

This maintains loose coupling and testability.

Sources: src/ChainedBatch.php75-77 src/ChainedBatch.php120-122


Summary

The ChainedBatch class enables sophisticated batch-and-chain compositions by:

  • Wrapping PendingBatch instances as queueable jobs
  • Recursively processing nested batch structures with prepareNestedBatches()
  • Converting back to PendingBatch during execution via toPendingBatch()
  • Integrating with job chains through finally callbacks that dispatch remaining jobs
  • Propagating chain metadata (connection, queue, catch callbacks) appropriately
  • Respecting batch cancellation to prevent unwanted chain continuation

This architecture allows batches to participate seamlessly in sequential job execution patterns while maintaining full batch functionality including callbacks, failure handling, and job tracking.

Sources: src/ChainedBatch.php1-131