title: Lazy-loading collections in zend framework
body: <p>I'm currently working on a simple budgeting application as a personal project. It is built on Zend Framework and uses an MVC architecture and the data mapper pattern. Controllers store and receive domain model entities via the data mappers and pass them to the view. The data mappers execute prepared statements via the Zend Db Adapter.</p>
  
  <p>The domain model consists of Users, who have many transactions and many budget categories. Each transaction can be assigned to a category.</p>
  
  <p>The architecture works well enough for simple CRUD operations but has a couple of serious drawbacks:</p>
  
  <ul>
  <li>First of all performance. A User object is instantiated for every request, and the data mapper automatically pulls all budget categories for that user from the database. These in turn pull their child transaction records from the database. This is obviously inefficient.</li>
  <li>Secondly, there is a lot of code in the controllers when dealing with multiple model entities or a subset of entities, such as a set of transactions from a certain time period. I am unsure as to where to put this code.</li>
  </ul>
  
  <p>Lazy-loading seems the obvious solution to the performance problem. But I am unsure as to how to implement this with the data mapper and with collections of objects. In particular, how should lazy-loading work when client code only requests a sub-set of a collection?</p>