https://book.cakephp.org/3.0/en/controllers/request-response.html
use Cake\Http\CallbackStream;
public function foo()
{
$items = $this->items->find()->limit(10);
$this->response->type(['csv' => 'text/csv']);
$this->response = $this->response->withType('csv');
$this->response = $this->response->withDownload('foo.txt');
$stream = new CallbackStream(function () use ($items) {
foreach ($items as $item) {
echo $item->id . ',' . $item->name . "\n";
}
});
$this->response = $this->response->withBody($stream);
return $this->response;
}
メモリー利用方法までは確認できていませんが、そこが問題無ければフレームワークに用意されているのであれば積極的に利用した方がよさそうですね。
ちなみにヘッダー出力は $this->response->withHeader() を利用しなさいって事になってるようです。