PHP Iterators and Streams are awesome

Fabien Potencier

May 21, 2010

A lot of people complain about "problems" with PHP as a language (function name inconsistencies, register_globals, and much more).

But PHP also have a lot of awesome features; at least two of them are in my opinion largely underused: Iterators and Streams. You won't learn how to use them in this post, but with a simple example, I hope you will want to learn more about them.

Some weeks ago, I have rewritten the old sfFinder class for Symfony 2 using Iterators. It was a really great experience and it makes for a very extensible Finder Component.

The Finder class has been designed to be used to find files and directories locally on your machine. But there is more. What if I want to use the same interface for some Amazon S3 bucket? Is it possible? Of course it is, thanks to streams:

use Symfony\Components\Finder\Finder;
$s3 = new \Zend_Service_Amazon_S3($key, $secret);
$finder = new Finder();
$finder->name('photos*')->size('< 100K')->date('since 1 hour ago');
foreach ($finder->in('s3://bucket-name') as $file) {
    // do something
    print $file->getFilename()."\n";

Want to learn more? Read the documentation about Iterators and Streams on


gravatar Kennethvr  — May 21, 2010 13:39   #1
nice one! practical, easy and straight forward. I like it!
gravatar Evert Harmeling  — May 21, 2010 13:43   #2
One word: Horny!
gravatar T-Moe  — May 21, 2010 14:01   #3
It's one thing, how nice features like Iterators and Streams are in a language like PHP, but the other thing is how they are used in the implementations and I have to say: Fabien, you really make a lot out of these features and use them in the best possible way

I also enjoy your well-written and technically striking blog posts. Keep up the good work.
gravatar Palleas  — May 21, 2010 14:06   #4
W00t, that's just awesome!
gravatar hakre  — May 24, 2010 00:34   #5
always propagate those two and then throw SPL exceptions! thanks!
gravatar Daniel Del Rio  — May 26, 2010 22:46   #6
I'm not completely sure what these streams and iterators are but this does make me want to learn more about them. Great post and keep up the good work!
gravatar Javier López  — June 10, 2010 14:01   #7
Looks so easy!

I needed to learn some about PHP Streams for my ZEND Certification exam and they still looks like black magic for me, ;) IMHO the PHP Doc is not very good at that point (unless it has been updated)
gravatar Peter C.  — June 28, 2010 15:00   #8
@Javier López: The docs in the manual are far from perfect at the moment, but the basic APIs should be more of less OK . Lots of the docs are still the automatically generated skeletons based on Reflection so, for those, things like return/parameter types should be taken with a pinch of salt.