Welcome to the Treehouse Community

The Treehouse Community is a meeting place for developers, designers, and programmers of all backgrounds and skill levels to get support. Collaborate here on code errors or bugs that you need feedback on, or asking for an extra set of eyes on your latest project. Join thousands of Treehouse students and alumni in the community today. (Note: Only Treehouse students can comment or ask questions, but non-students are welcome to browse our conversations.)

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and a supportive community. Start your free trial today.

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);
    }
}

1 Answer