PHP Designing Interfaces in PHP Using Interfaces Implementing Interface Methods

Alexei Parphyonov
Alexei Parphyonov
34,128 Points

If You Follow the Code from the Video and It Didn't Work, Here's a Solution

I do not use workspaces and followed along in VSC. The PHP versions are slightly different (0.1.0 difference). At the same time the code from the video did not work.

First, the iteration through $content (which is an object) was made possible by implementing the Iterator interface and adding those 5 methods.

In order to fix this problem, I went to the Docs on Iterator and used an example code from there, which actually makes more explanatory sense.

For everybody, who faced the same problem, here is the working code:

<?php

class Collection implements Iterator, Countable
{
    protected $repo;

    public $collection;
    private $position = 0;

    public function __construct(RepositoryInterface $repo, $id = null, $field = 'id')
    {
        $this->position = 0;
        $this->repo = $repo;
        if (!empty($id)) {
            $this->collection = $this->repo->find('posts', $id, $field);
        } else {
            $this->collection = $this->repo->all('posts');
        }
    }

    public function current()
    {
        var_dump(__METHOD__);
        return $this->collection[$this->position];
    }
    public function key()
    {
        var_dump(__METHOD__);
        return $this->position;
    }
    public function next()
    {
        var_dump(__METHOD__);
        $this->position += 1;
    }
    public function rewind()
    {
        var_dump(__METHOD__);
        $this->position = 0;
    }
    public function valid()
    {
        var_dump(__METHOD__);
        return isset($this->collection[$this->position]);
    }
    public function count()
    {
        return count($this->collection);
    }
}