friends. I know, there are many questions here already on these iterators.
I’ve read something, and I’m not a beginner… but my mind is somewhat stuck on this. Please, help me to comprehend how I use iterators in practice.
Suppose, I have an ORM object that can select instances from database. And one instance contains fields and can insert, uodate etc. As usual.
I want to iterate through all objects of a type, but as there can be plenty of them, I prefer to select them by “pages”. My code:
$limit = 100;
$offset = 0;
do
{
$recs = $orm->select($filter, $sorting, $limit , $offset);
$offset += $limit;
foreach ($recs as $rec)
{
// doing something with record
}
}
while (count($recs) == $limit);
I feel that iterator paradigm is what suits here, but what interface is better to implement in this case or maybe some base SPL class?
UPDATE
Ideally code above with iterator may look like:
$iterator = new ORMPagedIterator($ormobject, $filter, $sorting);
foreach ($iterator as $rec)
{
// do something with record
}
E.g. all that page by page behavior is inside the iterator.
I would use an Iterator that iterates over another Iterator and asks for a next Iterator once it reaches the end of the previous Iterator… ok, sounds a mo complicated than it actually is:
And here is a sample Implementation of that NextIteratorCallbackIterator:
UPDATE: Your ORMPagedIterator can be implemented using NextIteratorCallbackIterator as easy as: