Generators are one of the new cool stuff on
PHP 5.5, but it’s not a new feature in software programming languages, for example it’s on
Python since version 2.2 on 2001 and now in the draft
They are a simple and powerful tool for creating
iterators. They are like regular functions but using the
yield statement whenever they want to return data. A
generator looks like a function but behaves like an iterator, it’s useful for
lazy evaluation “which delays the evaluation of an expression until its value is needed”.
Here are some examples in different languages:
In this examples you would notice that we are using the keyword
yield instead of
return will pass value to the function caller then the function will finish the execution,
yield will pass a value then pause the execution of the function “which now became a generator” till the function caller ask for the next value. Then
yield again and again will return values to the function caller.
Using generators is useful in cases where you want iterations on demand, and you will end up with less resources consumption and also still the chance to send some data back to the generator function on any given iteration.
When you have situations that you are fetching large sets of data, you can use generators to
lazy load (“lazy load is to post pone fetching data till the point that you actually need it) your data sets or doing a lot of computation with big amounts of data.
Imagine that you have the code to execute a query on the database, instead of fetching and returning the whole data at the same time, you can simply return a generator function containing the query cursor that yields one data row at a time.
Finally you need to consider some stuff before start using
Generator, beware that once it get consumed you cannot reset it, you will need to recall it again.
Also keep resources like db connection and file stream busy on the
Generator function could be a problem if you are heavily use this resources and you need to release it as soon as possible.