drupal-code-generator icon indicating copy to clipboard operation
drupal-code-generator copied to clipboard

Add a command to generate batch service

Open bhanu951 opened this issue 1 year ago • 3 comments

Please add a command to generate batch service. Currently there is no command to generate batch class. Hence we need to code same boilerplate code again and again. Please Create a generator class to generate batch service.

bhanu951 avatar Apr 01 '24 07:04 bhanu951

Hi @bhanu951

Proposed Solution

Introduce a new generator command: generate:batch-service, which will create a batch service class with the required structure to use Drupal's Batch API.


namespace {{ namespace }};

use Drupal\Core\Batch\BatchBuilder;
use Drupal\Core\StringTranslation\StringTranslationTrait;

class {{ class }} {
  use StringTranslationTrait;

  public function buildBatch(array $items) {
    $batch_builder = new BatchBuilder();
    $batch_builder
      ->setTitle($this->t('Processing items...'))
      ->setFinishCallback([$this, '{{ finished_callback|default("finished") }}']);

    foreach ($items as $item) {
      $batch_builder->addOperation([$this, '{{ operation_callback|default("processItem") }}'], [$item]);
    }

    return $batch_builder->toArray();
  }

  public function {{ operation_callback|default("processItem") }}($item, array &$context) {
    // TODO: Implement batch processing logic.
  }

  public function {{ finished_callback|default("finished") }}(bool $success, array $results, array $operations) {
    if ($success) {
    // TODO: Implement batch processing logic.

    }
    else {
    // TODO: Implement batch processing logic.

    }
  }
}

Lets me know if you any suggestion, Other wise I would start working on feature

harivansh0 avatar Apr 25 '25 04:04 harivansh0

@harivansh0

Lets me know if you any suggestion, Other wise I would start working on feature

I think it looks good.

bhanu951 avatar Apr 29 '25 06:04 bhanu951

Hi @bhanu951 can you please review MR : https://github.com/Chi-teck/drupal-code-generator/pull/207

harivansh0 avatar May 20 '25 05:05 harivansh0