朋友。我知道,这些迭代器已经有很多问题了。 我读过一些东西,而且我不是初学者......但是我的思绪有点紧张。请帮助我理解我在实践中如何使用迭代器。
假设我有一个可以从数据库中选择实例的ORM对象。一个实例包含字段,可以插入,uodate等。像往常一样。 我想迭代一个类型的所有对象,但由于可能有很多,我更喜欢用“pages”选择它们。我的代码:
$limit = 100;
$offset = 0;
do
{
$recs = $orm->select($filter, $sorting, $limit , $offset);
$offset += $limit;
foreach ($recs as $rec)
{
// doing something with record
}
}
while (count($recs) == $limit);
我觉得迭代器范式适合这里,但是在这种情况下或者某些基础SPL类可以更好地实现什么接口?
更新 理想情况下,使用迭代器编写的代码可能如下所示:
$iterator = new ORMPagedIterator($ormobject, $filter, $sorting);
foreach ($iterator as $rec)
{
// do something with record
}
E.g。所有逐页行为都在迭代器中。
答案 0 :(得分:4)
我会使用迭代另一个迭代器的Iterator,并在它到达前一个Iterator的末尾时请求下一个Iterator ...好吧,听起来比实际上复杂:
<?php
$limit = 100;
$offset = 0;
$iter = new NextIteratorCallbackIterator(function($i) use ($orm, $limit, &$offset) {
printf("selecting next bunch at offset %d\n", $offset);
$recs = $orm->select($filter, $sorting, $limit , $offset);
$offset += $limit;
if ($recs) {
return new ArrayIterator($recs);
}
return null; // end reached
});
foreach ($iter as $rec) {
// do something with record
}
?>
以下是NextIteratorCallbackIterator的示例实现:
<?php
class NextIteratorCallbackIterator implements Iterator {
private $_iterator = null;
private $_count = 0;
private $_callback;
public function __construct($callback) {
if (!is_callable($callback)) {
throw new Exception(__CLASS__.": callback must be callable");
}
$this->_callback = $callback;
}
public function current() {
return $this->_iterator !== null ? $this->_iterator->current() : null;
}
public function key() {
return $this->_iterator !== null ? $this->_iterator->key() : null;
}
public function next() {
$tryNext = ($this->_iterator === null);
do {
if ($tryNext) {
$tryNext = false;
$this->_iterator = call_user_func($this->_callback, ++$this->_count);
}
elseif ($this->_iterator !== null) {
$this->_iterator->next();
if ($this->_iterator->valid() == false) {
$tryNext = true;
}
}
} while ($tryNext);
}
public function rewind() {
$this->_iterator = call_user_func($this->_callback, $this->_count = 0);
}
public function valid () {
return $this->_iterator !== null;
}
}
?>
更新:您的ORMPagedIterator可以使用NextIteratorCallbackIterator实现,就像这样简单:
<?php
class ORMPagedIterator implements IteratorAggregate {
function __construct($orm, $filter, $sorting, $chunksize = 100) {
$this->orm = $orm;
$this->filter = $filter;
$this->sorting = $sorting;
$this->chunksize = $chunksize;
}
function iteratorNext($i) {
$offset = $this->chunksize * $i;
$recs = $this->orm->select($this->filter, $this->sorting, $this->chunksize, $offset);
if ($recs) {
return new ArrayIterator($recs);
}
return null; // end reached
}
function getIterator() {
return new NextIteratorCallbackIterator(array($this,"iteratorNext"));
}
}
?>