title: Using generators with model entities that are formed by ORM or hydrated from database
body: <p>Use of PHP generators allows more efficient use of memory. All of tutorials use examples where a number is incremented and is <code>yield</code>'ed from a foreach() loop.</p>
  
  <p>But how do I use generators in a more complex way described below.</p>
  
  <pre class="lang-php prettyprint-override"><code>class Book {
  }
  
  class Library 
  {
      /**
       * @var Books[]
       */
      private $books;
  
      public function loadBooks()
      {
          // We load individual Books from database and form our "Book" objects
          // and push them into $this-&gt;books;
      }    
  
      public function getBooks()
      {
          foreach ($this-&gt;books as $book) {
              yield $book;
          }
      }
  }
  
  $library = new Library();
  $library-&gt;loadBooks();
  </code></pre>
  
  <p><strong>Question</strong>:</p>
  
  <p>How does the use of <code>yield</code> there make any difference at all to the required amount of memory? Didn't we already spend memory required to store every book inside <code>$this-&gt;books</code>?</p>
  
  <p>Are generators useful in such cases, when you are dealing with objects composed of another objects that come from database/ORM?</p>