Hi,
Sorry for the cheesy title π
I've been gradually building a lightweight file class for some work I'm doing at the moment. One issue I came accross was needing to do different things to different files, like caching or processing as a CSV file or stuff like that. Being a good little, pattern friendly boy I decided to abstract out this extra functionality using the Strategy pattern. However, it didn't quite scratch my itch hard enough, the key problem being that I needed a cached CSV file (processing 300Mb+ product database feeds). The sollution, I used the Decorator pattern to allow for a filter chain which could be extended at runtime (you can even alter the filter chain half way through reading from/ writing to a file!). I've attached a zip with it all (You can either re-implement my load function or replace it with the relevent requires/includes) and below is a short usage example.
Note: This is for PHP4, the interface could be improved quite a lot for PHP5 (fluid interface for setting fitlers anyoneπ)
<?php
// Create a readonly file
$file =& new File( '/path/to/test.csv' );
// Add the csv filter
$file->appendFilter( new Filter_CSV() );
// Then read it in
while( $line = $file->get() ) {
print_r($line);
}
// More complex scenario --
// Let's say we're wanting to read from one csv file and write out to another one, but the writing one needs caching.
// We could create the object like this
$read =& new File( '/path/to/read.csv' );
$read->appendFilter( new Filter_CSV() );
$write =& new File( '/path/to/write.csv', 'w+' );
$write->appendFilter( new Filter_Caching() );
$write->appendFilter( new Filter_CSV() );
// Or we could simply take advantage of PHP4's default, cloning capabilities and create them like this
// Create an empty file object
$file =& new File();
// Attach the csv filter
$file->appendFilter( new Filter_CSV() );
// Clone for the read object
$write = $read = $file;
// Handle each individually
$read->open( '/path/to/read.csv' );
$write->appendFilter( new Filter_Caching() );
$write->open( '/path/to/write.csv', 'w+' );
while( $line = $read->get() ) {
// do something with $line
$write->put( $line );
}
// Because of the register_shutdown_function in File::open we don't even need to flush or close the files :)
?>