Is it advisable to implement an Iterator for handling directory structures in PHP?

When dealing with directory structures in PHP, implementing an Iterator can be a useful approach to efficiently iterate through the files and directories. By using an Iterator, you can encapsulate the logic for traversing the directory structure and make it easier to work with the files and directories.

class DirectoryIterator implements Iterator {
    private $directory;
    private $files;
    private $index;

    public function __construct($directory) {
        $this->directory = $directory;
        $this->files = scandir($directory);
        $this->index = 0;
    }

    public function current() {
        return $this->files[$this->index];
    }

    public function key() {
        return $this->index;
    }

    public function next() {
        $this->index++;
    }

    public function rewind() {
        $this->index = 0;
    }

    public function valid() {
        return isset($this->files[$this->index]);
    }
}

// Example usage
$iterator = new DirectoryIterator('/path/to/directory');

foreach ($iterator as $file) {
    echo $file . PHP_EOL;
}