Using Dependency Injection within BatchService doesn't work

Created on 1 April 2022, about 3 years ago
Updated 19 May 2023, almost 2 years ago

Problem/Motivation

As raised in #3159239: Error: Using $this when not in object context β†’ you can't use dependency injection within BatchService as the functions that get called are used as callbacks, so you don't really have access to $this within the scope of the processMyNode or processMyNodeFinished. The entirety of the code added in that file is completely misleading. For example if I wrote the following, it wouldn't work, and you can't inject services within create/construct since they never actually get fired. There is no "service" here at all.

protected $connection;

public function __construct(Connection $connection) {
    $this->connection = $connection;
}

public static function create(ContainerInterface $container) {
  return new static(
    $container->get('database'),
  );
}
public function process($chunk, $batchId, $operation_details, &$context) {
  $context['message'] = $operation_details;
  foreach ($chunk as $instance) {
    $this->processFieldInstance($instance, $context);
  }
}

public function processFieldInstance($instance, &$context) {
  $query = $this->connection->select($instance['table'], 't')
    ->condition('t.bundle', $instance['entity_bundle'], '=')
    ->condition('t.entity_id', $instance['entity_id'], '=')
    ->condition('t.revision_id', $instance['entity_revision_id'], '=')
    ->execute();
}

Steps to reproduce

1. Try making your batch callback use $this to call another method within the BatchService class.
2. Or try using a service via dependency injection

Proposed resolution

Not really sure, research leads to #2875151: [META] Implement Batch API as a service β†’ which if you follow the rabbit hole you need to do things like in this post, https://www.previousnext.com.au/blog/refactoring-drupal-batch-api-callba...

Remaining tasks

Discuss, and 100% don't refer to the file as a service when it is not. It's just a class, that isn't current even instantiated since the methods are called directly via call_user_func_array().

πŸ› Bug report
Status

Active

Version

2.0

Component

Code

Created by

πŸ‡ΊπŸ‡ΈUnited States devkinetic

Live updates comments and jobs are added and updated live.
Sign in to follow issues

Comments & Activities

Not all content is available!

It's likely this issue predates Contrib.social: some issue and comment data are missing.

Production build 0.71.5 2024