Welcome to the Treehouse Community
Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.
Looking to learn something new?
Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.
Start your free trialAlexei Parphyonov
34,128 PointsIf 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
Jeffrey Perkinson
PHP Development Techdegree Graduate 14,474 PointsAlexei++, thank you. Mine wasn't working before this.