Iterator Pattern
iterator

Iterator Pattern

The Iterator pattern is a design pattern that allows you to traverse a collection of objects without exposing its underlying representation. It provides a common interface for accessing the elements of different types of collections, such as arrays, lists, trees, etc.

The Iterator pattern is useful when you want to decouple your logic from the data structure that you are iterating over. For example, you may want to perform some operation on each element of a collection, but you don't care about how the collection is stored or organized internally. By using an iterator, you can abstract away the details of the collection and focus on the logic of your operation.

One use case for the Iterator pattern is when you want to access data from different social networks, such as Facebook, Twitter, LinkedIn, etc. Each social network may have its own way of storing and representing user profiles, but you want to treat them uniformly and iterate over them in a consistent way. To achieve this, you can use the Iterator pattern to create a common interface for accessing user profiles from different social networks.

To implement the Iterator pattern in PHP, you need to define two interfaces: SocialNetworkInterface and ProfileIteratorInterface. The SocialNetworkInterface defines the methods for creating an iterator for a specific social network. The ProfileIteratorInterface defines the methods for accessing the elements of a collection using an iterator.

Here is an example of how to implement the Iterator pattern for Facebook:

class Facebook implements SocialNetworkInterface
{
    public function __construct(public array $profiles)
    {

    }

    public function getIterator(): ProfileIteratorInterface
    {
        return new FacebookIterator($this);
    }
}        
class FacebookIterator implements ProfileIteratorInterface
{
    private int $currentPosition = 0;

    public function __construct(public Facebook $facebook)
    {

    }


    public function hasNext(): bool
    {

        return isset($this->facebook->profiles[$this->currentPosition]);

    }

    public function getNext()
    {

        if ($this->hasNext()) {
            return $this->facebook->profiles[$this->currentPosition++];
        }
        return null;

    }
}
        

The Facebook class represents a collection of user profiles from Facebook. It implements the SocialNetworkInterface and provides a method for creating a FacebookIterator. The FacebookIterator class implements the ProfileIteratorInterface and provides methods for accessing the elements of the Facebook collection.

To use the Iterator pattern, you can create an instance of the Facebook class and pass it an array of user profiles. Then, you can create an iterator from the Facebook instance and use it to traverse the collection. For example:

<?php


use Iterator\Facebook;

require_once __DIR__ . '/Facebook.php';

$user_profiles = [
    [
        'name' => 'John Doe',
        'email' => 'john@test.com',
       ],
    [
        'name' => 'Jane Doe',
        'email' => 'jane@test.com',
    ],
];

$profiles = new Facebook($user_profiles);
$profileIterator = $profiles->getIterator();


while ($profileIterator->hasNext()) {
    $profile = $profileIterator->getNext();
    echo $profile['name'] . ' - ' . $profile['email'] . PHP_EOL;
}
// output
This code will output:

John Doe - john@test.com
Jane Doe - jane@test.com        

The Iterator pattern allows you to iterate over the user profiles from Facebook without knowing or caring about how they are stored or represented internally. You can also easily extend this pattern to other social networks by implementing their own classes and iterators that conform to the same interfaces.

If you want to learn more about the Iterator pattern and see other examples in PHP, you can check out this

GitHub page: https://github.com/Adams-Ijachi/design-patterns

You can also watch this YouTube video that explains the concept and implementation of the Iterator pattern: https://www.youtube.com/watch?v=uNTNEfwYXhI&list=PLrhzvIcii6GNjpARdnO4ueTUAVR9eMBpc&index=17

To view or add a comment, sign in

More articles by Adam Ijachi

  • Null State Pattern

    Unpacking the Null State Pattern Definition: The Null State pattern is a behavioral design pattern that provides an…

  • State Pattern

    Are you tired of dealing with monolithic code that becomes a tangled mess as your project grows? Design patterns are…

  • Composite Design Pattern

    A composite design pattern is a structural design pattern that allows you to compose objects into tree structures and…

  • Template Method Design

    Hi everyone! In this blog post, I'm going to talk about the template method pattern, a very useful design pattern in…

  • Proxy Design Pattern

    Hey there, welcome to my blog! Today I'm going to talk about the proxy pattern, what it is, when to use it, and how it…

  • Adapter Design Pattern

    Hey everyone, welcome to my blog! Today I want to talk about one of my favorite design patterns: the Adapter pattern…

  • Command Design Pattern

    The command pattern is a behavioral design pattern that allows you to encapsulate a request as an object and execute it…

  • Singleton Design Pattern

    The singleton pattern is a design pattern that ensures that only one instance of a class exists in the application. It…

  • Factory Design Pattern

    Hi there, welcome to my blog! Today I will talk about one of the most useful design patterns in software development:…

    2 Comments
  • Decorator Design Pattern

    Hi everyone, Today, I want to talk about the decorator design pattern, what it is, when to use it, and what are its…

Explore content categories