VOOZH about

URL: https://deepwiki.com/hypervel/bus/5.3-batchable-trait

⇱ Batchable Trait | hypervel/bus | DeepWiki


Loading...
Menu

Batchable Trait

Purpose and Scope

The Batchable trait enables jobs to access and interact with their parent batch during execution. When a job is dispatched as part of a batch, this trait provides methods to retrieve the batch instance, query its state, and make decisions based on batch status. This trait is primarily used by jobs that need batch-aware behavior, such as conditional execution based on batch cancellation or progress tracking.

For information about creating and dispatching batches, see Creating and Managing Batches. For information about other job traits, see Dispatchable Trait and Queueable Trait.


Overview

The Batchable trait adds batch-awareness capabilities to job classes. When included in a job, it automatically tracks the batch ID and provides convenient methods to access the parent Batch instance and query its state.

Trait Location and Structure


Sources: src/Batchable.php1-93 src/Batch.php1-363


Properties

The Batchable trait adds two properties to job classes:

PropertyTypeVisibilityPurpose
$batchId?stringpublicStores the UUID of the parent batch
$fakeBatch?BatchFakeprivateStores a fake batch for testing

Property Definition

The $batchId property is automatically set when jobs are dispatched as part of a batch. This occurs in two places:

  1. When PendingBatch dispatches jobs: each job has withBatchId() called on it
  2. When jobs are added to an existing batch via Batch::add(): the batch ID is assigned

Sources: src/Batchable.php15-23


Core Methods

batch(): Retrieving the Batch Instance

The batch() method retrieves the Batch instance for the job's parent batch. It returns null if the job is not part of a batch.

Method Signature:


Resolution Logic Flow


Sources: src/Batchable.php25-41

Implementation Details:

The method follows a priority resolution order:

  1. Fake Batch (lines 30-32): If $fakeBatch is set (used in testing), return it immediately
  2. Real Batch (lines 34-38): If $batchId is set, resolve BatchRepository from the DI container and call find($batchId)
  3. No Batch (line 40): Return null if neither condition is met

The use of ApplicationContext::getContainer() at src/Batchable.php35-37 ensures the repository is resolved from the Hyperf DI container, maintaining loose coupling.

Sources: src/Batchable.php25-41


batching(): Checking Batch Status

The batching() method determines whether the job's batch is still active and processing. It returns false if the batch has been cancelled or if the job is not part of a batch.

Method Signature:


Usage Pattern:


Sources: src/Batchable.php43-51

Common Use Cases:

Jobs can use batching() to conditionally execute logic:


The method checks two conditions:

  1. A batch exists (via $this->batch())
  2. The batch is not cancelled (via !$batch->cancelled())

Sources: src/Batchable.php43-51 src/Batch.php289-302


withBatchId(): Setting the Batch ID

The withBatchId() method assigns a batch ID to the job. This method is called internally by the batch system and is typically not invoked by user code.

Method Signature:


Batch ID Assignment Flow


Sources: src/Batchable.php53-61

Assignment Contexts:

The batch ID is assigned in two scenarios:

  1. Initial Batch Dispatch: When PendingBatch dispatches jobs, it calls withBatchId() on each job before pushing to the queue
  2. Adding Jobs to Existing Batch: When Batch::add() adds more jobs, it assigns the batch ID to new jobs at src/Batch.php87

The method returns static to maintain method chaining compatibility with other configuration methods.

Sources: src/Batchable.php53-61 src/Batch.php70-106


Testing with Fake Batches

The Batchable trait includes built-in support for testing through the withFakeBatch() method, which creates a fake batch without requiring database persistence or queue infrastructure.

Method Signature:


Fake Batch Creation Process


Sources: src/Batchable.php63-92

Test Usage Example:

The method is designed for unit testing scenarios where you need to verify batch-aware behavior without infrastructure dependencies:


Key Features:

  1. Default Values: Empty strings and zeros for optional parameters simplify common test cases
  2. UUID Generation: Automatically generates a unique ID if not provided (line 79)
  3. Current Timestamp: Uses CarbonImmutable::now() for createdAt if not specified (line 86)
  4. Tuple Return: Returns both the job and fake batch for convenient test setup (line 91)

Sources: src/Batchable.php63-92


Integration with Batch System

The Batchable trait serves as the interface between individual jobs and the batch processing system. Understanding this integration is crucial for effective batch-aware job design.

Batch-Job Interaction Architecture


Sources: src/Batchable.php25-51 src/Batch.php136-254


Usage Patterns

Pattern 1: Conditional Execution Based on Batch Status

Jobs can check if their batch has been cancelled before performing expensive operations:


Implementation Location: This pattern is used when jobs need to respect batch cancellation. The job calls batching() at src/Batchable.php46-51 which internally checks if the batch exists and is not cancelled via src/Batch.php299-302

Sources: src/Batchable.php43-51 src/Batch.php289-302


Pattern 2: Accessing Batch Progress Information

Jobs can query their parent batch to access progress metrics:

MethodReturn TypeDescription
batch()->progress()intPercentage complete (0-100)
batch()->processedJobs()intNumber of completed jobs
batch()->totalJobsintTotal jobs in batch
batch()->pendingJobsintJobs still pending
batch()->failedJobsintNumber of failed jobs

Sources: src/Batch.php120-134


Pattern 3: Dynamic Job Addition

Jobs can add more jobs to their own batch during execution:


Implementation: The job retrieves its batch via batch() at src/Batchable.php28-41 then calls add() at src/Batch.php70-106 to dynamically expand the batch.

Sources: src/Batchable.php25-41 src/Batch.php70-106


Property and Method Reference

Complete Method Summary

MethodReturn TypePurposeVisibility
batch()?BatchRetrieve parent batch instancepublic
batching()boolCheck if batch is activepublic
withBatchId(string)staticSet the batch IDpublic
withFakeBatch(...)arrayCreate fake batch for testingpublic

Sources: src/Batchable.php1-93


Relationship to Batch Lifecycle

The Batchable trait participates in the complete batch lifecycle:


Key Integration Points:

  1. Batch Assignment (line 56-60): The withBatchId() method is called during dispatch
  2. Runtime Access (line 28-41): The batch() method provides access during execution
  3. State Checking (line 46-51): The batching() method enables cancellation-aware behavior

Sources: src/Batchable.php25-61 src/Batch.php136-254


Dependency Resolution

The trait relies on Hyperf's dependency injection container to resolve the BatchRepository:

Resolution Mechanism


Container Resolution: At src/Batchable.php35-37 the trait uses ApplicationContext::getContainer()->get(BatchRepository::class) to resolve the repository. This approach:

  • Maintains loose coupling (depends on interface, not implementation)
  • Leverages Hyperf's service provider configuration
  • Enables testability through container mocking

Sources: src/Batchable.php35-37


Summary

The Batchable trait provides the essential interface for jobs to interact with their parent batch. Through its simple API—batch(), batching(), and withBatchId()—jobs gain batch-awareness while maintaining clean separation of concerns. The trait handles repository resolution, state checking, and provides testing support through fake batches, making it straightforward to implement batch-aware job logic.

Sources: src/Batchable.php1-93 src/Batch.php1-363