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?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With