I'm dealing with code that renders HTML pages. I'm cleaning up an old, messy PHP code base.

Let's say I have a template that loops through a long list of rows in a database. I can load my data into an array and pass that array to the template in order to separate the view from the other logic, or I can pass in the PDOStatement object, which is a Traversable (insert any language's iterable interface here), which will receive rows as it loops.

Is the second method approprate?

It seems like it should be appropriate to me, there is no logic in the template, it uses a foreach, just like it would with an array, but the difference is, under the hood, each of the iterations of the loop are pulling data from a database. If an error were to occur, it's too late to handle it well after the headers and part of the page have been sent.

1 Answer 1


If it gives a performance advantage or it makes implementing and maintaining the system easier then having then having the template code cause the database to retrieve data is fine.

You should be able to rely on your database. An error is unlikely to occur, particularly once the query has started. Indeed if you were to use an ORM such as Doctrine or Eloquent, then just getting data from one of your objects could easily trigger a new database query. Doctrine generates its own PHP classes that inherit from yours but query the db when necessary, and silently inserts them in to your application. Eloquent expects you to write classes that inherit from its base class with the capacity to query the database when necessary.

One note of caution though - you probably don't want to directly tie the front end templating layer to the database structure, unless its a very simple application. So instead of passing PDOStatement itself I would pass some other domain object which is or can return some form of generator or Traversable.

  • I'm using $stmt->setFetchMode(\PDO::FETCH_CLASS, $className); to get PDO to return my model's type and a bunch of AS's in the SQL to make it match up, so it's not dependent on the SQL structure, but that's a good note.
    – duckbrain
    Commented Jul 31, 2018 at 19:47

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.