1

I've been studying this book on php and there's this example on the iterator pattern which uses the iterator interface. I can use the iterator interface to loop through simple arrays but I don't quite understand the example illustrated in the book. I'll post snippets of the code. It says instead of doing something like this.

<?php
$posts = getAllPosts(); //example function return all post ids of this author
for($i = 0; $i<count($posts); $i++) 
{
$title = getPostTitle($post[$i]);
echo $title;
$author = getPostAuthor($post[$i]);
$content = parseBBCode(getPostContent($post[$i]));
echo "Content";
$comments = getAllComments($post[$i]);
for ($j=0; $j<count($comments); $j++)
{
$commentAuthor = getCommentAuthor($comments[$j]);
echo $commentAuthor;
$comment = getCommentContent($comments[$j]);
echo $comment;
}
}
?>

We can implement the iterator interface to provide something more effective

<?php
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
foreach ($comments as $comment)
{
echo $comment->getAuthor();
echo $comment->getContent();
}
}
?>

Now I dont understand why the $blogposts was never used, why it isn't part of the methods of any class and what kind of data it will return, an array or an object.

I also dont understand how the $post->getTitle() is acheived. I'd understand $post['title'] or $posts->getTitle() since we can add a getTitle() method to the Posts class.

I'd really love to replicate something like this on something I'm working on

doing

foreach($key as $value) {
    $value->getTitle();
}

instead of

foreach($key as $value) {
    $value['title'];
    //or
    $key->getTitle()
}
Youngestdj
  • 53
  • 11

1 Answers1

1

It seems a typo I think it shoud be

$blogposts = getAllPosts();
$posts = new Posts($blogposts);

Regarding to the accesd to getTitle method I need more code to answer the question properly... But I it will work if the function "getAllPosts" returns an array of Post object which implement the method "getTitle()"

Hope it helps!

darode
  • 140
  • 6