Skip to content

Instantly share code, notes, and snippets.

@hakre
Created March 13, 2013 13:35
Show Gist options
  • Save hakre/5152090 to your computer and use it in GitHub Desktop.
Save hakre/5152090 to your computer and use it in GitHub Desktop.
CachtingIterator for a PDOStatement with support for multiple iterations.
<?php
/**
* Class CachedPDOStatement
*
* CachingIterator for a PDOStatement
*/
class CachedPDOStatement extends CachingIterator
{
private $index;
public function __construct(PDOStatement $statement) {
parent::__construct(new IteratorIterator($statement), self::FULL_CACHE);
}
public function rewind() {
if (NULL === $this->index) {
parent::rewind();
}
$this->index = 0;
}
public function current() {
if ($this->offsetExists($this->index)) {
return $this->offsetGet($this->index);
}
return parent::current();
}
public function key() {
return $this->index;
}
public function next() {
$this->index++;
if (!$this->offsetExists($this->index)) {
parent::next();
}
}
public function valid() {
return $this->offsetExists($this->index) || parent::valid();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment