J
J
JackShcherbakov2018-03-04 16:18:10
PHP
JackShcherbakov, 2018-03-04 16:18:10

Where can PHP iterators come in handy?

Hello!
For several hours now I can not understand what the advantage of the classes is. I did not find a clear answer. In all the examples that I saw, a class was created that implements Iterator and it had an array property that was passed through. Why all this dance with a tambourine when there is a simple foreach? Can you please give me a normal example that will show the advantage and indispensable use of these iterators.
Thanks in advance!

Answer the question

In order to leave comments, you need to log in

1 answer(s)
K
Kirill Nesmeyanov, 2018-03-04
@JackShcherbakov

Well, since we need examples, I'll come up with something ...
The task is the following. It is necessary to make requests to the API for all available pages, well, I don’t know, for example, we get articles from habr. The algorithm is as follows:
- We work until the page is the last
one - We get a list of articles and start returning them.
- As soon as they run out, we check if the current page is the last one.
And so on until the page ends.

class HabraArticles implements \IteratorAggregate 
{
    // ...
    // Какие-то методы настроек апишки
    // ...

    public function getIterator(): iterable
    {
        $page = 0;

        do {
            $response = // запрос_к_апи?page=$page++
            yield from $response['articles'];
        } while ($response['last_page'] !== $page);
    }
}

And use. We create a new object of our api and set it up. As soon as we start to run through it through foreach, the necessary interface method is called automatically (in our case, getIterator, since the IteratorAggregate interface was used).
$articles = (new HabraArticles)
    ->какой_то_метод_настроек(23)
    ->ещё_какой_то_метод_настроек(42);

foreach($articles as $article) {
    \var_dump($article); // Пробегаемся по всем существующим статьям и не думаем о том, как оно работает.
}

The symfony finder, for example, is implemented in a similar way: symfony.com/doc/current/components/finder.html

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question