Brian, On Sun, Aug 12, 2012 at 4:08 PM, Brian Moon <br...@moonspot.net> wrote:
> Hi Nikita, > > I admit, I have ignored these threads as there was no RFC. So, some of > this may have been covered. > There was an RFC in those posts... It was just being iterated over. > Do you have a good example usage other than a file? I don't find > fopen/fgets/fclose all that complicated. What are the other valid use cases > for such a thing? > Here's a quick set of examples: http://blog.ircmaxell.com/2012/07/what-generators-can-do-for-you.html > Also, not allowing rewinding is unintuitive for something that is an > iterator in PHP. If I can foreach() it and I can call next() on it, I > expect to be able to reset() it as well. IMO, you would need to issue a > FATAL PHP error if that simply is not allowed. Or you have to have a second > syntax for what to do in that case. At that point, you are implementing > Iterator. > I partially agree. rewinding the generator might be possible, but it's hard to tell in those cases. It's hard to tell if resetting it is even possible from the code level. So I'm pretty much OK with living with that restriction for the time being... > While I am glad that PHP has borrowed syntax from many languages, I find > the yield keyword to be very WTF when I first saw it. It is also poorly > explained in your RFC. You use terms like "sending and receiving". That > does not say "returns from function execution" to me. I had to basically > figure it out from the code examples. > It's absolutely something that takes getting used to. But it's also quite intuitive once you think about it. You're not "returning" back to the parent scope (exiting your scope), you're "yielding" a value to the parent scope, expecting to continue on later (think of it as a stop light where you let the other code run for a while until you go to the next one). > Lastly, because you cite needing this for sending data to PHPUnit, I think > this is a user land problem and not a core problem. In about 5 minutes I > implemented a reusable Generator object that does exactly what you need. > http://pastebin.com/V336rEpR At least, it does what your examples show > you need. Again, file IO is very easy and perhaps that example does not > explain your true need very well. > Well, there's one thing that should be made clear. There's nothing (and I mean that) that generators provide that you can't do already. You can build iterators that do exactly the same thing. The trick that generators provide you is a really short, and really easy way of implementing iterators. You don't need to worry about maintaining state or anything like that. All you need to do is code it how you would normally, and replace your executing code with a yield. No more needing to split out and maintain state in weird ways, or using literally hundreds of lines of code (because of the boilerplate involved) where a dozen would do... Anthony