Skip to content
Advertisement

Using generators with model entities that are formed by ORM or hydrated from database

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?

Advertisement

Answer

While your example takes no profit from yield, than for the answer of your question is: it depends.

Given you keep inside your object a handle to a result, you might gain if instead of loading all records into property, you yield them.

There are also ORMs that do collect relational data on the fly, so that while having a defined relation between tables, their retrieving full result from table 1, and then building separate selects for details of table 2 if needed. In this case, you should gain from yield especially while your trying to display collection huge enough to use all your process memory. It’s possible because databases have their internal “cursors” to read data back and forth, so if you instead of loadng everything into memory are using those cursors, you can process lots more data than your memory would keep. And yield happen to be very helpful than.

Nevertheless yield is not that much useful with ORMs, because most popular ORMs are made also for quite optimal resource usages. In your case I would rather focus on properly using your ORMs, than utilizing fancy techniques.

User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement