PHP has a history of using functions for iteration, but there is now a push to use objects in PHP 5. The Iterator Pattern is not language specific and doesn't need any language enhancements to create. The added benefit in PHP 5 is that objects are allowed in foreach loops with the SPL Iterator interface.
The Iterator Pattern is not constrained to the class which holds the data and can aggregate the iterator implementation to another object. The aggregated class provides iteration implementation separate from the main class. Aggregation of the Iterator is the best practice for optimizing overhead.
The Iterator Pattern allows you to control how the data is passed to the developer in the loop and what methods they call. The pattern is a standard that creates a smoother transition and easier for the developer. They will know which methods to call for an action without having to look up method name in your reference manual.
When using the Iterator Pattern, you should only collect the information that you need.
The Iterator Pattern allows for accessing the current element and allowing the retrieval of additional elements in a loop routine or manually in a code block.
This function will create an array and return it for testing the Iterators.
For the Iterator object, we are going to get the full list and also allow for multiple pages implementation. This object uses mysql queries to get user list and go through the list.
To use the Iterator, it easy if you use the foreach loop.
There is also an array version for doing a similar action. It will work with any mysql fetched array, or a user created array.
The execution of the Iterator expected behavior will only work in the foreach loop.
Most will use the next method in the while loop. With the default behavior, it will continue on ignoring the limit and page rules.
The valid method has to be called to stay within the ruleset of the iterator. This is the wanted behavior for those who wish to bypass the ruleset of the iterator, which can't be done in the foreach loop.
Iterators don't save you from poor interface methods' implementations and poor optimizations. Using the Iterator Pattern will decrease the speed of the script over the procedural method, but if done right it should be minimal and predictable.
Separation of the iteration and main class functionality adds to the code reuse and speed for which projects can be developed. They are an useful tool for managing data and controlling how a developer has access.