Search code examples
phppdophp-generators

Iterating over generators with while


I'm writing a PDO wrapper for a new project. A very common pattern with SQL is to write a statement such as

while ($row = $connection->fetch($sql)) {
    ...
}

My wrapper function is essentially this:

public function fetch($query, $bindings)
{
    $stmt = $this->getPdo()->prepare($query);

    $stmt->execute($bindings);

    $stmt->setFetchMode($this->getFetchMode());

    foreach ($stmt as $record) {
        yield $record;
    }
}

But I can't use the values if I call this using a while loop as above. Doing a var_dump says that $row is a Generator object. If I use a foreach, a var_dump shows the database data, as expected. Is it simply not possible to traverse over generators using while, or have I confused myself here somewhere?


Solution

  • Is it simply not possible to traverse over generators using while, or have I confused myself here somewhere?

    You have confused yourself ;) In your code sample:

    while ($row = $connection->fetch($sql)) {
    

    You actually execute fetch() for every iteration of the loop. With generators you typically use foreach():

    foreach ($connection->fetch($sql) as $row) {