Skip to content

Instantly share code, notes, and snippets.

@alairock
Last active February 3, 2017 19:31
Show Gist options
  • Save alairock/12b3d2f749acce53ef7ab919a069fe4c to your computer and use it in GitHub Desktop.
Save alairock/12b3d2f749acce53ef7ab919a069fe4c to your computer and use it in GitHub Desktop.
Using a Generator in PHP. Helpful when you need to work on hundreds....thousands....millions of records. Don't load them all into memory all at once. Work on them one at a time!
<?php
$usersQuery = \App\User::query();
$usersQuery->where('type', '=', 'client');
foreach(generate($usersQuery) as $user) {
// Do something with that user
}
<?php
function generate($query) {
$sql = $query->toSql();
$bindings = $query->getBindings();
$pdo = \DB::connection()->getPdo();
$stmt = $pdo->prepare($sql);
$stmt->execute($bindings);
while ($row = $stmt->fetch(\PDO::FETCH_ASSOC)) {
yield $row;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment