<?php
/**
* An example of flat file database, using almost csv format
* Over simplified
*
*/
class FlatFile
{
/**
* Filename of file being worked with
*
* @var string
*/
var $filename ;
/**
* Field delimiter
*
* @var char
*/
var $delimiter ;
/**
* Number of columns per line
*
* @var int
*/
var $columns ;
/**
* Handle to filename
*
* @var resource
*/
var $handle ;
/**
* Array of cached data
*
* @var array
*/
var $data ;
/**
* Construct a FlatFile object
*
* @param string $filename
* @param int $columns
* @param char $delimiter
*/
function __construct( $filename, $columns, $delimiter = ',' )
{
$this->filename = $filename ;
$this->delimiter = $delimiter ;
$this->columns = $columns ;
$this->data = array( );
$this->handle = null ;
if( file_exists( $filename ) )
{
foreach( file( $filename ) as $num => $line )
{
if( ( $data = explode( $this->delimiter, $line, $this->columns ) ) )
{
$this->data[ ] = array_map( 'trim', $data ) ;
}
}
}
}
/**
* Add a line to the cache
*
* @param array $array
*/
function line( $array )
{
if( count( $array ) === $this->columns )
{
$this->data[ ] = $array;
}
}
/**
* Write cached data to this->filename
*
* @return boolean
*/
function save( )
{
if( ( $this->handle = fopen( $this->filename, 'w+' ) ) )
{
/**
* Probably should lock the file for exclusive access while writing what could be a world of data
*/
flock( $this->handle, LOCK_EX );
while( ( $line = array_shift( $this->data ) ) )
{
if( count( $line ) and !fwrite( $this->handle, sprintf( "%s\r\n", implode( sprintf( '%s ', $this->delimiter ) , $line) ) ) )
{
return;
}
}
fclose( $this->handle );
return true;
}
}
/**
* Retrieve parsed cache
*
* @return array
*/
function data( )
{
if( count( $this->data ) )
{
return $this->data ;
}
}
}
/**
* New object of type FlatFile
*/
$csv = new FlatFile( 'file.db', 4 );
/**
* Write a couple of lines to cached data
*/
$csv->line( array(
"John",
"Watkins",
"23",
"Male"
) );
$csv->line( array(
"The",
"Other Guy",
34,
"Male"
) );
/**
* Write out to csv
*/
$csv->save( );
/**
* Reset
*/
$csv = null ;
/**
* Reopen
*/
$csv = new FlatFile( 'file.db', 4 );
/**
* Output nice data
*/
echo "<table width=\"100%\">\n";
echo "\t<tr>\n";
echo "\t\t<th>First</th>\n";
echo "\t\t<th>Last</th>\n";
echo "\t\t<th>Age</th>\n";
echo "\t\t<th>Sex</th>\n";
echo "\t</tr>\n";
foreach( $csv->data as $id => $line )
{
echo "\t<tr>\n";
printf( "\t\t<td>%s</td\n", $line[0] );
printf( "\t\t<td>%s</td>\n", $line[1] );
printf( "\t\t<td>%s</td>\n", $line[2] );
printf( "\t\t<td>%s</td>\n", $line[3] );
echo "\t</tr>\n";
}
echo "</table>\n";
?>