朋友们.我知道,这些迭代器已经存在很多问题.
我读过一些东西,但我不是初学者…但是我对此有些犹豫.请帮助我理解在实践中如何使用迭代器.
假设我有一个ORM对象,可以从数据库中选择实例.一个实例包含字段,并且可以插入,uodate等.
我想遍历一个类型的所有对象,但是由于可以有很多对象,因此我更喜欢通过“页面”来选择它们.我的代码:
$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
}
例如.所有的逐页行为都在迭代器内部.
解决方法:
我将使用一个迭代器,该迭代器在另一个迭代器上进行迭代,并在到达上一个迭代器的末尾时请求下一个迭代器…好吧,听起来确实比实际复杂:
<?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"));
}
}
?>