ชุดประมวลผลรายการทั้งหมด แต่แทนที่จะแสดงข้อความเสร็จสิ้น ฉันเห็นข้อผิดพลาด "ขนาดหน่วยความจำที่อนุญาตของ 536870912 ไบต์หมดแล้ว"
เมื่อฉันดีบักโค้ด ฉันสังเกตเห็นว่า Drupal โหลดบล็อกที่ประมวลผลแต่ละบล็อกเมื่อเสร็จสิ้นแบทช์ (ContentEntityBase->__สร้าง). ฉันไม่เข้าใจว่าทำไม Drupal ถึงทำเช่นนั้น
โครงสร้างของรหัส:
นี่คือโมดูลแบบกำหนดเองที่มีคลาสฟอร์มและฟังก์ชันแบทช์ใน custom_module.module ไฟล์.เมื่อส่งแบบฟอร์ม โมดูลจะเรียกฟังก์ชันสร้างแบทช์:
ฟังก์ชันสาธารณะ submitForm (อาร์เรย์ &$form, FormStateInterface $form_state) {
  custom_module_make_batch();
}
ฟังก์ชัน custom_module_build_batch รับรหัสของบล็อกแบบกำหนดเอง (4000 หรือมากกว่า) และสร้างแบทช์:
ฟังก์ชัน custom_module_make_batch()
{
  $ชุด = [];
  $items = get_blocks_ids();
  $batch = custom_module_generate_batch($รายการ);
  batch_set($แบทช์);
}
ฟังก์ชัน custom_module_generate_batch($รายการ)
{
  $การดำเนินการ = [];
  $operations_groups = array_chunk($รายการ, 50);
  foreach ($operations_groups เป็น $key => $operations_group) {
    $การดำเนินการ[] = [
      'custom_module_batch_op',
      [$operations_group],
    ];
  }
  $ ชุด = [
    'operation' => $operation,
    'เสร็จสิ้น' => 'custom_module_batch_finished',
    'title' => 'แบทช์กำหนดเอง',
    'init_message' => 'แบทช์กำลังเริ่มต้น',
    'progress_message' => 'ประมวลผล @current จาก @total ส่วน',
    'error_message' => 'แบทช์พบข้อผิดพลาด',
  ];
  ส่งคืน $ ชุด;
}
ฟังก์ชัน custom_module_batch_op($operations_group, &$context) {
  foreach ($operations_group เป็น $key => $bid) {
  
    $block = \Drupal::service('entity.repository')->loadEntityByUuid('block_content', $bid);
    $block->field_name = $new_value;
    
    $block->save();
  }
}
ฟังก์ชัน custom_module_batch_finished($success, $results, $operations)
{
  $messenger = \Drupal::messenger();
  ถ้า ($ สำเร็จ) {
    // ที่นี่เราสามารถทำสิ่งที่มีความหมายกับผลลัพธ์ได้
    // เราเพียงแค่แสดงจำนวนโหนดที่เราประมวลผล...
    ถ้า ($ ทั้งหมด) {
      $messenger->addMessage(t('@count ผลลัพธ์ที่ประมวลผลแล้ว', ['@count' => $total]));
    } อื่น {
      $messenger->addMessage(t('ไม่มีรายการสำหรับการย้ายข้อมูล'));
    }
  } อื่น {
    // เกิดข้อผิดพลาด.
    // $operations ประกอบด้วยการดำเนินการที่ยังไม่ผ่านการประมวลผล
    $error_operation = รีเซ็ต ($ การดำเนินการ);
    $messenger->addMessage(
      เสื้อ(
        'เกิดข้อผิดพลาดขณะประมวลผล @operation พร้อมอาร์กิวเมนต์: @args'
        [
          '@operation' => $error_operation[0],
          '@args' => print_r($error_operation[0], จริง),
        ]
      )
    );
  }
}