使用php迭代器接口迭代数据库结果

时间:2017-07-09 01:10:56

标签: php mysql iterator spl

我一直在研究这本关于php的书,并且在使用迭代器接口的迭代器模式上有这个例子。我可以使用迭代器接口循环遍历简单数组,但我不太明白本书中说明的示例。我将发布代码片段。它说不是做这样的事情。

<?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;
}
}
?>

我们可以实现迭代器接口来提供更有效的东西

<?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);
}
}
?>

“现在让我们使用我们刚刚创建的迭代器。”

<?
$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();
}
}
?>

现在我不明白为什么$blogposts从未使用过,为什么它不是任何类的方法的一部分,它将返回什么样的数据,数组或对象。

我也不明白$post->getTitle()是如何实现的。我理解$post['title']$posts->getTitle(),因为我们可以在Posts类中添加getTitle()方法。

我真的很想在我正在研究的东西上复制这样的东西

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

而不是

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

1 个答案:

答案 0 :(得分:1)

我认为这似乎是一个错字

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

关于访问getTitle方法,我需要更多的代码才能正确回答问题...但是如果函数“getAllPosts”返回一个实现方法“getTitle()”的Post对象数组,它将会起作用

希望它有所帮助!