Skip to content

topics.iocollections

Alex Kiesel edited this page Jun 7, 2012 · 7 revisions

I/O: Collections

The I/O collections API provides interfaces to work with collections of I/O elements, usually files and folders.

Element

An I/O element is defined by the io.collections.IOElement interface.

An element has:
  • A URI (uniform resource identifier)
  • A size (in bytes)
  • A creation date
  • A date when it was last accessed
  • A date when it was last modified

Collection

A collection is defined by the io.collections.IOCollection interface, which extends the IOElement interface. Ontop of the IOElement attributes, a collection has the following methods to iterate on its contents.

Iteration

Instead of having to recurse through folder trees, the io.collections.iterate.IOCollectionIterator class produces a flat list of all elements.

Example: Listing folder contents

<?php
  $origin= new FileCollection('/etc');
  for ($i= new IOCollectionIterator($origin); $i->hasNext(); ) {
    Console::writeLine('Element ', $i->next());
  }
?>

The above example will recurse into subdirectories if the iterator instanciation is changed to:

<?php
  new IOCollectionIterator($origin, TRUE);
?>

Filters

To narrow the list of returned elements, one can exchange the IOCollectionIterator with the io.collections.iterate.FilteredIOCollectionIterator class.

Date-based filters

  • io.collections.iterate.AccessedAfterFilter
  • io.collections.iterate.AccessedBeforeFilter
  • io.collections.iterate.CreatedAfterFilter
  • io.collections.iterate.CreatedBeforeFilter
  • io.collections.iterate.ModifiedAfterFilter

Name-based filters

  • io.collections.iterate.NameMatchesFilter
  • io.collections.iterate.NameEqualsFilter
  • io.collections.iterate.ExtensionEqualsFilter

Size-based filters

  • io.collections.iterate.SizeBiggerThanFilter
  • io.collections.iterate.SizeEqualsFilter
  • io.collections.iterate.SizeSmallerThanFilter

Combinations filters

  • io.collections.iterate.NegationOfFilter
  • io.collections.iterate.AllOfFilter
  • io.collections.iterate.AnyOfFilter

Example: Finding images

<?php
  $origin= new FileCollection('/home/thekid/multimedia');  
  $filter= new ExtensionEqualsFilter('.jpg');
  $recursive= FALSE;
  
  foreach (new FilteredIOCollectionIterator($origin, $filter, $recursive) as $element) {
    Console::writeLine('Element ', $element);
  }
?>

Collection composite

Example (all files in /home and /usr):

<?php
  $collection= new CollectionComposite(array(
    new FileCollection('/home'),
    new FileCollection('/usr')
  ));

  foreach (new IOCollectionIterator($origin)) {
    Console::writeLine('Element ', $i->next());
  }
?>

History

I/O Collections were first introduced within xp-framework/rfc#75 - RFC 0075 - in October 2006 and enhanced later on in xp-framework/rfc#77 - RFC 0077.