Using the new io.collections API

at 2006-09-21 in RFCsExamples by friebe (0 comments)

How many times have you written something like the following to recursively traverse directories?

<?php 
function allClassesIn(&$folder) {
$files= array();
while
(FALSE !== ($e= $folder->getEntry()) {
$qualified= $folder->getURI().$e;
if
(is_dir($qualified)) {
$files= array_merge($files, allClassesIn(new Folder($qualified)));
} else if (preg_match('/\.class\.php$/', $qualified)) {
$files[]= $qualified;
}
}
$folder->close();
return
$files;
}

$classes= allClassesIn(new Folder('/home/thekid/devel/xp/'));
?>

With the implementation of RFC #0075, this has become a lot easier (and even more generic).

Continue reading for details...

Using the new io.collections API, you can rewrite the above example to the following:

<?php 
function allClassesIn(&$collection) {
$files= array();
for
(
$i= &new FilteredIOCollectionIterator($collection, new RegexFilter('/\.class\.php$/'), TRUE);
$i->hasNext();
) {
$element= &$i->next();
$files[]= $element->getURI();
}
return
$files;
}

$classes= allClassesIn(new FileCollection('/home/thekid/devel/xp/'));
?>

Notes:
  • The allClasses() function will work for any IOCollection implementation - e.g., a collection based on a zip archive or a .tar.gz-file.
  • If you need more complex matching rules, you can supply your own implementation of the IterationFilter interface (though RegexFilter is currently the only existing implementation, the most common usecases will be covered by new classes soon)



Subscribe

You can subscribe to the XP framework's news by using RSS syndication.


Categories

News
General
PHP5
Announcements
RFCs
Further reading
Examples
Editorial
EASC
Experiments
Unittests
Databases
5.8-SERIES

Related

Find related articles by a search for «Using».