Skip to content

Instantly share code, notes, and snippets.

@eguicciardi
Last active November 2, 2020 02:17
Show Gist options
  • Save eguicciardi/f4499b9892b5eeda869678861d381b03 to your computer and use it in GitHub Desktop.
Save eguicciardi/f4499b9892b5eeda869678861d381b03 to your computer and use it in GitHub Desktop.
Drupal 7.x Batch API example tied with a Drush command
<?php
function mymodule_setup_batch($start=1, $stop=100000) {
$dataset = array(); // A very large dataset
$chunks = array_chunk($dataset, 20); // Divide the dataset
$operations = array();
$count_chunks = count($chunks);
$i = 1;
// Let's define what to do on every chunk
foreach ($chunks as $chunk) {
$i++;
$operations[] = array("mymodule_simple_function" , array( $chunk ,'details'=> t('(Importing chunk @chunk of @count)', array('@chunk '=>$i, '@count'=>$count_chunks))));
$operations[] = array("mymodule_another_simple_function", array( $chunk ));
}
// Put everynthing in an array to setup the batch
$batch = array(
'operations' => $operations,
'title' => t('Import batch'),
'init_message' => t('Initializing'),
'error_message' => t('An error occurred'),
'finished' => 'mymodule_finished_method'
);
// Get the batch process all ready!
batch_set($batch);
$batch =& batch_get();
// Our terminal window doesn't need to know the progress of the operations
$batch['progressive'] = FALSE;
// Start processing the batch operations.
drush_backend_batch_process();
}
function mymodule_simple_function($chunk, $operation_details, &$context) {
// Do something interesting
$context['message'] = $operation_details; // We will show what we are working on
}
function mymodule_another_simple_function($chunk, &$context) {
// Do something even more interesting
$context['message'] = t('We have done a second thing to a chunk of data');
}
function mymodule_finished_method($success, $results, $operations) {
// Done!
print t('Finished! Bye bye!');
}
function mymodule_drush_command() {
$items = array();
$items['myimport'] = array(
'callback' => 'mymodule_setup_batch',
'description' => dt('Import'),
'arguments' => array(
'start' => "start",
'stop' => "stop",
),
);
return $items;
}
function mymodule_drush_help($section) {
switch ($section) {
case 'drush:myimport':
default:
return dt("import items from the Internal Database [start record] [end record].");
break;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment