Re: Iterators?
| From: | Harry Fuecks | Date: | Mon, 23 Jun 2003 01:29:04 +0000 |
| Subject: | Re: Iterators? | ||
| References: | 1 2 | Groups: | php.pear.dev |
| Request: | Send a blank email to pear-dev+get-17630@lists.php.net to get a copy of this message | ||
On Mon, 23 Jun 2003 08:41:27 +0800, Alan Knowles <alan@akbkhome.com> wrote:
It's pretty clear that classic iterators are not that usefull. as they are provided by the language.Very true. I find myself simply adding a common get of method names to classes where there's data to be looped through. Basically what you're saying with the have an Iterator interface. Perhaps the other way to go would be to make the package a standard which people should try to use when possible, without requiring it be directly referred to in code. One iterator I came across recently which I thought was interesting as it manages to provide an API more or less common to an indexed iterator while still deferring to the sequences PHP maintains looks something like this; <?php class ArrayIterator { var $atStart = true; var $array; var $element; function ArrayIterator($array) {
$this->array = $array;} function next() {
if ($this->atStart) {
$element = reset($this->array);
$this->atStart = false;
} else {
$element = next($this->array);
}
if (is_array($element)) {
$this->element = $element;
return true;
} else {
$this->element = null;
return false;
}
} function get($key) {
return $this->element[$key];} function reset() {
$this->atStart = true;} } ?> Of course for an array it doesn't add much value over accessing the array directly but I liked the trick in the next() method which returns the current element (courtesy of PHP's reset() function) it the array pointer is at the start. The intention is to provide an iterator for associative arrays. It's possible to adapter PEAR::DB_Result to this interface quite nicely (although DB_Result doesn't seem to have a way to reset a query so it means performing the query again, each time the iterator is reset). I'll put together a collection of all the PHP iterators I've run into later, just for comparison.