Skip to content

Instantly share code, notes, and snippets.

@mia-0032
Created December 26, 2012 04:05
Show Gist options
  • Save mia-0032/4377752 to your computer and use it in GitHub Desktop.
Save mia-0032/4377752 to your computer and use it in GitHub Desktop.
Iteratorパターン
<?php
interface MyIterator {
public function hasNext();
public function next();
}
class MovieShelf {
private $movies = array();
public function setMovie(array $movie) {
$this->movies[] = $movie;
}
public function getTitle($index) {
return $this->movies[$index]['title'];
}
public function getLength() {
return count($this->movies);
}
public function iterator() {
return new MoviesIterator($this);
}
}
class MoviesIterator implements MyIterator {
private $movieshelf;
private $index;
public function __construct(MovieShelf $movie_shelf) {
$this->movieshelf = $movie_shelf;
$this->index = 0;
}
public function hasNext() {
if ($this->movieshelf->getLength() > $this->index) {
return true;
} else {
return false;
}
}
public function next() {
$title = $this->movieshelf->getTitle($this->index);
$this->index++;
return $title;
}
}
$movie_shelf = new MovieShelf;
$movie_shelf->setMovie(array('title' => 'ほげ01', 'img' => 'movie1.jpg'));
$movie_shelf->setMovie(array('title' => 'ほげ02', 'img' => 'movie2.jpg'));
$movie_shelf->setMovie(array('title' => 'ほげ03', 'img' => 'movie3.jpg'));
$movie_shelf->setMovie(array('title' => 'ほげ04', 'img' => 'movie4.jpg'));
$movie_shelf->setMovie(array('title' => 'ほげ05', 'img' => 'movie5.jpg'));
$movie_iterator = $movie_shelf->iterator();
while ($movie_iterator->hasNext()) {
echo $movie_iterator->next();
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment