Use of PHP generators allows more efficient use of memory. All of tutorials use examples where a number is incremented and is yield'ed from a foreach() loop.
But how do I use generators in a more complex way described below.
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->books;
}
public function getBooks()
{
foreach ($this->books as $book) {
yield $book;
}
}
}
$library = new Library();
$library->loadBooks();
Question:
How does the use of yield there make any difference at all to the required amount of memory? Didn't we already spend memory required to store every book inside $this->books?
Are generators useful in such cases, when you are dealing with objects composed of another objects that come from database/ORM?