Drupal Core recently updated the approach for defining batch operations to a more modern Object-Oriented Programming (OOP) approach. Here’s how to rewrite existing batch operation definitions using this new approach.
Writing batch process operations prior to Drupal 8.6 required developers to define an array for their batch processes along the lines of:
$batch = [
'title' => t('My long-running process'),
'operations' => [
[
'my_first_operation',
[
'parameter_1',
'parameter_2',
],
],
[
'my_second_operation',
[],
],
],
'finished' => 'my_finished_callback',
];
batch_set($batch);
As these definitions grew more complex their readability began to suffer – so many arrays, so much indentation! Fret no more, because since Drupal 8.6 developers can define their batch operations using an extremely readable object-oriented format provided by Core’s BatchBuilder
class.
Using BatchBuilder
, our previous array-based format becomes:
use Drupal\Core\Batch\BatchBuilder;
$batch_builder = new BatchBuilder();
$batch_builder->setTitle(t('My long-running process'))
->addOperation('my_first_operation', ['parameter_1', 'parameter_2'])
->addOperation('my_second_operation', [])
->setFinishCallback('my_finished_callback');
batch_set($batch_builder->toArray());
Where creating batches used to require tedious coding of difficult to interpret arrays, the new BatchBuilder
class allows developers to create batches using a clear, declarative format. The example shown above demonstrates a small set of the methods the BatchBuilder
class provides – everything a developer previously defined in their batch arrays now has an analogous method in the BatchBuilder
class.
One thing you may have noticed above is that, yes, batch_set()
does not accept the BatchBuilder object, but the BatchBuilder
class does provide a convenient method for converting the object to an array and BatchBuilder
objects can be easily passed around your code like any other PHP object.