What implementation of Iterator should be used in PHP and why?

I'm trying to reorganize a big old project, and one thing I noticed is a whole series of different Iterator implementations:

while($iterator->moveNext()) { $item = $iterator->current(); // do something with $item; } for($iterator = getIterator(), $iterator->HasNext()) { $item = $iterator->Next(); // do something with $item } while($item = $iterator->fetch()) { // do something with item } 

or even StandardPHPLibrary (SPL) , which allows

 foreach($iterator as $item) { // do something with $item } 

Having so many different Iterators (with different methods for iterating over collections) seems like a strong smell of code, and I tend to reorganize everything in SPL. Is there an inherent advantage to any of these Iterator implementations, or is it just a matter of personal taste?

+4
source share
2 answers

The SPL version is definitely the way to go. Not only is this the easiest to read, but now it is part of PHP, so it will be familiar to many other people.

There is nothing "wrong" with others, but, as you said, all these different versions in one project do not help anyone.

+9
source

Imo, just using one or more SPL libraries as an interface is usually less ugly to use on the front panel. However, implementation support can get a little ugly.

For example, I wrote an iterator that effectively repeated a set of database results, so that results that were never queried were never retrieved from the query pointer, and if the elements were prematurely selected (IE: $ obj [5]), this will look for everything necessary results to the internal buffer.

It worked wonderfully, you just pray that the code that makes magic backstage never fail because it confuses people when they see that you are using something like an array, and it does β€œmagic” that can fail fail :)

Magic made people burn at the stake. Therefore, use it carefully and wisely, it may be clear how this works.

My personal preferences relate to

 for( $object as $i => $v ) 

the designation for him is usually more consistent and predictable.

 for( $dbresult->iterator() as $i => $v ){ } 

the style designation is functionally identical, but at least you have less clue how it works on the surface.

+1
source

All Articles