Let us create an Iterator for
our post object.
Chapter 4
[ 83 ]
We will create a function named getAllPosts() that will return all posts from
the DB. All these posts are returned as a Post object, which has methods like
getAuthor(), getTitle(), getDate(), getComments(), etc. Now we will create
the Iterator:
class Posts implements Iterator
{
private $posts = array();
public function __construct($posts)
{
if (is_array($posts)) {
$this->posts = $posts;
}
}
public function rewind() {
reset($this->posts);
}
public function current() {
return current($this->posts);
}
public function key() {
return key($this->var);
}
public function next() {
return next($this->var);
}
public function valid() {
return ($this->current() !== false);
}
}
?>
Now let's use the Iterator we just created.
$blogposts = getAllPosts();
$posts = new Posts($posts);
foreach ($posts as $post)
{
echo $post->getTitle();
echo $post->getAuthor();
echo $post->getDate();
echo $post->getContent();
$comments = new Comments($post->getComments());
//another Iterator for comments, code is same as Posts
Design Patterns
[ 84 ]
foreach ($comments as $comment)
{
echo $comment->getAuthor();
echo $comment->getContent();
}
}
?>
The code becomes much readable and maintainable now.
Pages:
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103