Created
December 26, 2012 04:05
-
-
Save mia-0032/4377752 to your computer and use it in GitHub Desktop.
Iteratorパターン
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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