A monthly export building a four hundred thousand row array before writing a single byte.
public function rows(): Generator
{
foreach ($this->orders->lazyByMonth($this->month) as $order) {
yield [$order->reference, $order->total->format(), $order->placedAt];
}
}
// and the writer, streaming
$out = fopen('php://output', 'wb');
foreach ($this->rows() as $row) {
fputcsv($out, $row);
}
The generator only helps if the source is also lazy — a cursor rather than a fetched collection — and that is the half people miss, because the generator makes the code look streaming while the query has already loaded everything. Peak memory went from 1.8 GB to 22 MB, and the first byte reached the client in under a second instead of after ninety.