1

I can't get batch to work with a static method as callback function for the operation

$batch['operations'][] = ['MyController::MyMethod', [$arg]];

If I use a procedural function and call a static method from that, it works.

It could be a solution, but as I have several methods to call during the same batch, I don't want to create a wrapper function.

Does someone know how to make batch API work with static methods?

2

The function that Drupal uses to process the batch operation is _batch_process(), which uses the following code to call the operation callback.

  // Build the 'context' array and execute the function call.
  $batch_context = array(
    'sandbox'  => &$current_set['sandbox'],
    'results'  => &$current_set['results'],
    'finished' => &$finished,
    'message'  => &$task_message,
  );
  call_user_func_array($callback, array_merge($args, array(&$batch_context)));

Since call_user_func_array() allows to use a string like MyClass::myMethod as callback, the code you wrote should work, if the Drupal autoloading system is able to find the file containing the class definition, which means:

  • You need to respect the file structure as per the PSR4 structure expected by Drupal
  • You need to fully qualify the class name by adding its namespace

In the case the file containing the class it is not in the directory where Drupal looks for class files, such as in the case the class is contained in a my_operation_callbacks.inc put in the same directory containing the module file, then you need to use code similar to the example code shown in Batch operations.

$batch = array(
  'title' => t('Exporting'),
  'operations' => array(
    array('my_function_1', array($account->id(), 'story')),
    array('my_function_2', array()),
  ),
  'finished' => 'my_finished_callback',
  'file' => 'path_to_file_containing_myfunctions',
);

$batch['file'] in that code tells Drupal which file it needs to load before executing the operation callbacks.
Even in this case, the class must be referenced using its namespace, which could simply be \ in the case the class is put in the global namespace.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.