Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Which implementation of Iterator should I use in PHP, and why?

I'm trying to refactor a large, old project and one thing I've noticed is a range 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 the StandardPHPLibrary (SPL) iterator which allows

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

Having so many different Iterators (with different methods for looping over collections) seems like a strong code smell, and I'm inclined to refactor everything to SPL. Is there a compelling advantage to any of these implementations of Iterator, or is it purely a matter of personal taste?

like image 857
Ken Avatar asked Dec 30 '22 07:12

Ken


1 Answers

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

There's nothing "wrong" with the others, but as you stated, having all these different versions in one project isn't helping anyone.

like image 58
Greg Avatar answered Jan 05 '23 15:01

Greg