[TYPO3-dev] DB query iterator; worth a try?

Ernesto Baschny [cron IT] ernst at cron-it.de
Thu Apr 22 09:22:12 CEST 2010


Jigal van Hemert schrieb am 21.04.2010 14:08:
> I've been experimenting a bit with an iterator for queries (comments
> removed to save space):
> 
> class databaseIterator implements Iterator {
> 
>     private $position = 0;
>     private $res;
> 
>     public function  __construct($res = NULL) {
>         $this->res = $res;
>     }
> 
>     public function rewind() {
>         mysql_data_seek($this->res, 0);
>         $this->position = 0;
>     }
> 
>     public function current() {
>         return mysql_fetch_assoc($this->res);
>     }
> 
>     public function key() {
>         return $this->position;
>     }
> 
>     public function next() {
>         $this->position++;
>     }
> 
>     public function valid() {
>         return mysql_data_seek($this->res, $this->position);
>     }
> }
> 
> A function such as:
> 
> function exec_SELECTiterator ($select_fields, $from_table,
> $where_clause, $groupBy='', $orderBy='', $limit='') {
>     $res = $GLOBALS['TYPO3_DB']->exec_SELECTquery($select_fields,
> $from_table, $where_clause, $groupBy, $orderBy, $limit);
>     return new databaseIterator($res);
> }
> 
> Allows you to simply use a foreach directly on the iterator:
> 
> $res = $this->exec_SELECTiterator( ....parameters.... );
> foreach ($res as $row) {
>     // do what you want with the row
> }
> 
> Initial test seem to indicate that an iterator is slightly slower than
> the usual t3lib_db::sql_fetch_assoc(), but this could also be caused by
> the current implementation (mysql_data_seek() calls, transfer of
> resource to iterator object)
> I haven't compared it with exec_SELECTgetRows().
> 
> Worth further investigating? Any problems to be expected?

It should work. To make it perform just like regular fetch_assocs in a
row: In next() you should do the sql_fetch_assoc right away so that you
don't ever need to seek. A basic "foreach()" will just call next() +
current() in a row.

See [1] for an example on how to do it.

And use $TYPO3_DB->sql_data_seek and $TYPO3_DB->sql_fetch_assoc while
you are at it, so it is DBAL compliant.

Cheers,
Ernesto

[1] http://www.php.net/manual/de/class.iterator.php#89053




More information about the TYPO3-dev mailing list