Batch processing with Doctrine: toIterable(), flush() and clear()

Batch processing with Doctrine walks through thousands of entities without filling up memory: you read them one by one, and every N, you write then clear.

$numero = 0;
foreach ($io->progressIterate($query->toIterable(), $total) as $reservation) {
    $this->entityManager->remove($reservation);

    if (0 === ++$numero % self::PAR_LOT) {
        $this->entityManager->flush(); // write the batch…
        $this->entityManager->clear(); // … then forget the loaded entities
    }
}
$this->entityManager->flush(); // the last, incomplete batch
$this->entityManager->clear();

The EntityManager keeps in memory every entity it loads or has to write: with getResult(), the whole selection arrives at once, and the process grows with the ledger. toIterable() hydrates results one by one; flush() sends the batch's changes, clear() detaches everything Doctrine was tracking. Both traps raise no error. A clear() without a flush() right before also wipes the pending remove() and persist() calls: nothing is written. And without a flush() after the loop, the last incomplete batch is lost; with exactly 20 bookings for batches of 20 you don't see it, with 25 you do.

The exercises have you write the ledger's big clean-up, a command that purges finished bookings in batches, with a progress bar, a --dry-run mode and details with -v; then find out why, after Pipin's visit, it reports having purged everything while leaving dozens of old bookings in the ledger.

2 exercises work on this concept, by writing code in the browser.

In the tracks

Related concepts

DebuggingConsole commandExit codes