note 101381 added to class.iterator
| From: | kent at marketacumen dot com | Date: | Mon, 13 Dec 2010 21:15:50 +0000 |
| Subject: | note 101381 added to class.iterator | ||
| Groups: | php.notes | ||
| Request: | Send a blank email to php-notes+get-174888@lists.php.net to get a copy of this message | ||
For Iterators implement database queries, what I've found is that if you want to chain multiple
iterators together using a "MultipleIterator" then you *do not* want ::rewind() to
actually execute your query, especially if it's expensive.
Instead, what I've done is implement that portion in "valid."
e.g.
<?php
class Database_Result_Iterator {
...
private $_db_resource = null;
private $_loaded = false;
private $_valid = false;
function rewind() {
if ($this->_db_resource) {
mysql_free($this->_db_resource);
$this->_db_resource = null;
}
$this->_loaded = false;
$this->_valid = false;
}
function valid() {
if ($this->_loaded) {
$this->load();
}
return $this->_valid;
}
private function load() {
$this->_db_resource = mysql_query(...);
$this->_loaded = true;
$this->next(); // Sets _valid
}
}
?>
That way if you chain multiple queries in a "MultipleIterator" together, the
"rewind" call (which rewinds all iterators at once) does not execute every query at once.
In addition, I found that the MultipleIterator may now work best for other reasons, but still, the
above is a good idea to postpone queries until the last possible moment they are needed.
----
Server IP: 64.71.164.2
Probable Submitter: 96.245.89.9
----
Manual Page -- http://www.php.net/manual/en/class.iterator.php
Edit -- https://master.php.net/note/edit/101381
Del: integrated -- https://master.php.net/note/delete/101381/integrated
Del: useless -- https://master.php.net/note/delete/101381/useless
Del: bad code -- https://master.php.net/note/delete/101381/bad+code
Del: spam -- https://master.php.net/note/delete/101381/spam
Del: non-english -- https://master.php.net/note/delete/101381/non-english
Del: in docs -- https://master.php.net/note/delete/101381/in+docs
Del: other reasons-- https://master.php.net/note/delete/101381
Reject -- https://master.php.net/note/reject/101381
Search -- https://master.php.net/manage/user-notes.php