From 3b3e2b09f7afdba26129f0a52183471a8109bb98 Mon Sep 17 00:00:00 2001 From: Robert Sesek Date: Wed, 25 Jun 2008 10:14:33 -0400 Subject: [PATCH] Implement Iterator in BSDbResult * Db.php: Add $iterator ivar (BSDBResult::rewind): New method (BSDBResult::current): New method (BSDBResult::key): New method (BSDBResult::next): New method (BSDBResult::valid): New method --- CHANGES | 1 + Db.php | 82 ++++++++++++++++++++++++++++++++++++++++++++++++++++++++- 2 files changed, 82 insertions(+), 1 deletion(-) diff --git a/CHANGES b/CHANGES index 4e7e974..0cc47b1 100644 --- a/CHANGES +++ b/CHANGES @@ -8,3 +8,4 @@ - New: Made many private members protected or public - Change: Added BSPrinterAbstract::__toString() that merely calls paint() - Change: BSTemplate is completely redone +- New: Implement Iterator in BSDBResult diff --git a/Db.php b/Db.php index 20a1d50..5923e0e 100644 --- a/Db.php +++ b/Db.php @@ -346,7 +346,7 @@ abstract class BSDb * @package ISSO * */ -abstract class BSDbResult +abstract class BSDbResult implements Iterator { /** * The result resource @@ -354,6 +354,12 @@ abstract class BSDbResult */ protected $result; + /** + * All the results (as used by the iterator implementation) + * @var string + */ + protected $iterator; + /** * Sets the resource and returns a result object * @@ -364,6 +370,23 @@ abstract class BSDbResult $this->result = $result; } + /** + * Method to call on the result + * + * @param string Method name + * + * @return array Array of results + */ + public function fetchAll($method = 'fetchArray') + { + $results = array(); + while ($result = $this->$method()) + { + $results[] = $result; + } + return $results; + } + /** * Fetch the query result as an array * @@ -453,6 +476,63 @@ abstract class BSDbResult * @return integer Number of rows */ protected abstract function _numRows($result); + + // ################################################################### + // # Iterator implementation + // ################################################################### + /** + * Rewinds the iterator by resetting the result pointer + * + * @return void + */ + public function rewind() + { + if ($this->iterator == null) + { + $this->iterator = $this->fetchAll(); + } + reset($this->iterator); + } + + /** + * Returns the current row + * + * @return array + */ + public function current() + { + return current($this->iterator); + } + + /** + * Returns the key (result pointer index) + * + * @return integer + */ + public function key() + { + return key($this->iterator); + } + + /** + * Advances the iterator and returns the row + * + * @return array + */ + public function next() + { + return next($this->iterator); + } + + /** + * Checks whether the iterator is valid + * + * @return boolean + */ + public function valid() + { + return ($this->current() !== false); + } } /** -- 2.22.5