BlueShoes Application Framework made with PHP http://www.blueshoes.org/


Packageindex Classtrees Modulegroups Elementlist Report XML Files

File: C:/usr/local/lib/php/blueshoes-4.2/core/file/Bs_FileCache.class.php
BlueShoes Application Framework - file

Bs_FileCache

Bs_Object
   |
  +-- Bs_FileCache

File Cache Class.

 

public class Bs_FileCache extends Bs_Object

File Cache Class.
Like a lot of other caches and still a little different.Typical Use :o You have just crunched data typically from a file using a lot of CPU and want topersist the crunched data for later use.Also you want to be notified if the persisted data has become 'out of date' becausethe 'origin-file' has changed AND/OR the lifetime you have set has passed.- (This is also referred as "Hot Update").USAGE Samples#################################################################################################### Sample 1# --------# Use with default settings.# Crunch only when the 'origin-file' file changes.# *1*) Create the cacher.$cacher =& new Bs_FileCache(); // Create new Cacher# *2*) Try to get the cached data using the file-path as key.$data = $cacher->fetch('D:/tmp/toCrunchData.txt');# *3*) Test the return value, FALSE is error, NULL is "out of date"if ($data === FALSE) { // ERRORecho "ERROR: " . $cacher->getLastError();} elseif ($data === NULL){ // "Out Of Date" (or not cached)// Crunch the data (Replaced with *YOUR* crunching function.)$crunchedData = myCruncher('D:/tmp/toCrunchData.txt');# *4*) Cache the data as serialized data$cacher->store('D:/tmp/toCrunchData.txt', serialize($crunchedData));} else { // SUCCESS$crunchedData = unserialize($data);}// do something with $crunchedData################### Sample 2# --------# Use with some property settings.# This time there is no 'origin-file' file and we use a 'lifetime' for the cache.# *1*) Create the cacher and set properties.$cacher =& new Bs_FileCache(); // Create new Cacher$cacher->setDir('r:/'); // TIPP: Use a RAM-Disk !$cacher->setBufferSize('200k'); // % of memory is also possible$cacher->setVerboseCacheNames(TRUE); // Give cache-files a readable name# *2*) Try to get the cached data using any key *you* define.$MY_CACHE_KEY = 'chachKey_1';$data = $cacher->fetch($MY_CACHE_KEY);# *3*) Test the return value, FALSE is error, NULL is "out of date"if ($data === FALSE) { // ERRORecho "ERROR: " . $cacher->getLastError();} elseif ($data === NULL){ // "Out Of Date" (or not cached)// Crunch the data (Replaced with *YOUR* crunching function.)$crunchedData = myCruncher('D:/tmp/toCrunchData.txt');# *4*) Cache the data as serialized data with timeout of 600s and disable 'origin-file' check$cacher->store($MY_CACHE_KEY, serialize($crunchedData), $originCheck=FALSE, 600);} else { // SUCCESS$crunchedData = unserialize($data);}###################################################################################################CONTEXT:To avoid confusion with the cache-mechanism used in this object keep in mind that'cache' : Is used to describe the data you want written to a persitent media (a file).'buffer': Is used to describe the data brought into memory as optimization to avoidreading from the file (second level cache).FEATURES :o Checks if 'origin-file' has changed AND/OR the lifetime you have set has passed(cache then becomes 'out of date').o Cache versioning to identify outdated/invalid cache data.*All* cache with older versions then $cacheVersion are considered 'out of date'.Very useful during development and updates, where the structure of the data yougenerate has changed and all cache data becomes invalid. Saves you the hassle todelete all old cache files spread all over the disk.o Exclusive cache writing to disk.o Second level memory buffer that holds the cache data in memory for reuse(Currently only until script ends).o setBufferSize() : Ability to set the memory buffer size in bytes OR in % of theavailable script memory.o setDir() : Define where you want the cache-files to be stored. 2 optionsa) In one central dirb) Below each 'origin-file' in a subdir.o setVerboseCacheNames() : Define if the 'cache-files' should contain a verbose name or not.A verbose name contains the name of the 'origin-file' (max first 100 chars).BASICS:Second level caching (memory buffered data):Stored or fetched data is kept in memory as a fifo-list.(Unless the data size is larger then the max allowed memory buffer size).If buffer is too full then the first entries of the fifo-list are removeduntil enough space is available and the new data is added to the end of the list.Entrys are valid only for a limited time (default is 10 secs. See setBufferLifetime()).Older entrys trigger the 'up to date'-check and are reloaded from cache when fetched (this incl. ).+---------------------------+Application | Memory buffer | Diskdata stream <---> | (second level cache) | <----> cache-file| organized as Fifo-List |+---------------------------+'Up To Date'-Checking :If in store() the parameter $originCheck===TRUE (default) it is assumed that thepassed 'data stream' has it's origin in a data file that was crunched (or parsedor whatever) and that the cache is valid as long as the 'origin-file' exists andis not modified.An 'Up To Date'-check compares the mod-time of the 'origin-file' against themod-time of the 'cache-file'. If'origin-file-time' <= 'cache-file-time'the cache is considered 'up to date'.The 'Up To Date' check takes place every time the 'cache-file' has to be loadedinto the memory buffer.dependencies: Bs_Dir, Bs_File, Bs_UnitConverter

Authors,
Sincebs4.1
Version4.2.$id$
Copyrightblueshoes.org

 

Methods inherited from Bs_Object

isex, isexception, tostring, tohtml, persist, unpersist, bs_object, bbsetoutput, bbawake, bbisawake, bbxmsg, bbxfunctionstart, bbxfunctionend, bbxecho, bbxvar, bbxvardump, bbforcetrace, bbbufferstart, bbbufferget, bbbufferendflush, bbbufferendclean

Public Method Summary

void

Bs_FileCache([ mixed $cacheVersion ])

Constructor.
bool

isModifiedSince(string $filePath, int $since)

int

getLastModified(string $filePath)

void

flushFileCache()

kills all cached file content.

Private Method Summary

string

fetch(string $filePath)

Fetch the data stream that was once pushed into the cache.
void

store(string $filePath, string $dataStream, [ string $originCheck, string $maxLifeTime ])

Store the data stream to cache.
void

clearBuffer([ string $filePath ])

Clear the memory buffer (All or just one entry)
int

setBufferSize(mixed $newBufSize)

Set the size of the cache buffer
void

setBufferLifetime([ integer $sec ])

The max time a memory buffered data is considered 'up to date' befor an 'up to date'-check
void

setCacheLifeTime([ integer $sec ])

The max time until the cached data is considered 'out to date' even if the 'origin'-file
void

setDir([ string $path ])

Define where you want the cache-files to be stored.
void

setVerboseCacheNames([ string $trueFalse ])

Define if the 'cache-files' should contain a verbose name or not.
mixed

getLastError()

Get last error.
int

_getFiFoIndex( $filePath)

Find the index of the fifo-array matching $filePath
bool

_addToFiFo(array $cacheBlock)

Add $cacheBlock to fifo-array
void

_fifoFreeSpace( $sizeOfNewData)

Free up the fifo-array until $sizeOfNewData fits in.
void

_fifoGarbageCollect()

Get rid of entries in the fifo-array that are marked invalid
void

_determinePathToCache( $filePath)

Determine the cache-dir from the origin-dir and make the cache name.
bool

_isCacheFileUptodate( $filePath, $cacheFilePath)

'Up To Date' - checking:
void

_writeCacheFile( $cacheFilePath, $cacheBlock)

Write cache
void

_readCacheFile( $cacheFilePath)

Read cache

Private Field Summary

object [unknown]

$_bsFile

STATIC instance of Bs_File. gets instanced the first time in _writeCacheFile().
array

$_cacheProp

Internal cache properties
array

$_fifoBuffer

The second level cache as fifo list.
string

$_cacheVersion

The cache data has a version to identify outdated/invalid cache data.
string

$_lastErrMsg

contains the last error that occured and *is* reset after every *successfull* public function call.
array

$_errMsgHistory

for debugging. contains an error history that is *not* reset.
array

$_determineFileNameHash

Private Constant Summary

Bs_FILECACHE_VERSION >>4.0.$x$<< Warning: documentation is missing.

Public Method Details

Bs_FileCache

public void Bs_FileCache( [ mixed $cacheVersion ] )

  Constructor.
NOTE to $cacheVersion use:*All* cache with older versions are considerd 'out of date'. Very usefull during developmentand updates, where the structure of the data you generate has changed and all cache databecomes invalid. Saves you the hassle to delete all old cache files spread all over the disk.

Parameter
mixed $cacheVersion = >>0<<
sting or int. Cache data with other version is considered invalid.
Returns void


isModifiedSince

public bool isModifiedSince( string $filePath, int $since )

 

Parameter
string $filePath
int $since
(unix timestamp in GMT!!)
Returns bool

See Also getLastModified()

getLastModified

public int getLastModified( string $filePath )

 

Parameter
string $filePath
Returns int

(unix timestamp in GMT!!)

Throws bool FALSE if not cached.
See Also isModifiedSince()

flushFileCache

public void flushFileCache( )

  kills all cached file content.

Returns void


Private Method Details

fetch

private string fetch( string $filePath )

  Fetch the data stream that was once pushed into the cache.
The $filePath is used in 2 ways :a) As key to identify the cache.b) See store()(If in store() you set: $originCheck==TRUE) the full path to the 'origin-file' is used to look up the mod-time.(If in store() you set: $originCheck==FALSE) $filePath is 'just' a key to identify the cach. No file look ups.

Parameter
string $filePath
the full path to the 'origin-file'.
Returns string

The cached data on success OR NULL if data is out of date.

Throws FALSE on all errors. Check getLastError().

store

private void store( string $filePath, string $dataStream, [ string $originCheck, string $maxLifeTime ] )

  Store the data stream to cache.
The $filePath is used in 2 ways :a) As key to identify the cache.b) (If $originCheck==TRUE) is the full path to the 'origin-file' to look up the mod-time.(If $originCheck==FALSE) *no* 'origin-file' is assumed, but $maxLifeTime should be setto a int > 0. If not it will default to 24 houres. You can set a default $maxLifeTimewith setCacheLifeTime() or indivitually by passing a parameter.The cache is considered 'out of date' (see fetch()) if one of following happens:a) $maxLifeTime has passed.b) The 'origin-file' changes (and $originCheck is set to TRUE)Done by comparing the modified times of the 'cache-file' and the 'origin file'as given by the parameter $filePath. If cache-file is eqal age oryounger, cache is considered 'up to date'Why the need for a max lifetime? You may think "we can check if the originalfile is older than the cache file, that's enough". lemme give you 2 reasons:1) If there is *no* origin file at all. That's the case when we cache somecalcuated data or something out of a database.2) The origin data, may it come from a real file or not, may include alifecycle. In my case the data is made up from an xml property file of aproduct in an eShop. Now that product may become alive or may become obsoletewithout that the original file changes, so that my crunching function comes up witha different result over time.

Parameter
string $filePath
the full path to the 'origin-file'.
string $dataStream
the data to store.
string $originCheck = >>TRUE,<<
(default: TRUE) If we should check if the origin has modified. If FALSE don't even assume an existing origin file.
string $maxLifeTime = >>NULL<<
(default: see above). The max lifetime in secs for this cache. 0 = forever. NULL (default) = use the setting from setCacheLifeTime(). if nothing was set using setCacheLifeTime() then it's 0 (which means forever).
Returns void

Throws FALSE on all errors. Check getLastError().
See Also setCacheLifeTime()

clearBuffer

private void clearBuffer( [ string $filePath ] )

  Clear the memory buffer (All or just one entry)
If the passed $filePath is not empty, the whole memory buffer is cleared.Otherwise only the entry matching $filePath is marked as invalid (if found)and will not be used any more. (That means it will reloaded from file)

Parameter
string $filePath = >>''<<
the full path to the 'origin-file'.
Returns void


setBufferSize

private int setBufferSize( mixed $newBufSize )

  Set the size of the cache buffer
Data that is sorted or fetched will be buffered up to the given size.When buffer is full the oldest entry(s) is kicked out.Default is 5% of the available memory as given by 'memory_limit' in the php.ini file.No buffering: If 'memory_limit' is not set or if you pass 0.Buffering with no limit: If you pass -1. (Of corse your not able to exceed PHP 'memory_limit')NOTE:It is possible that data of one entry is larger then the buffer limit.It will *NOT* be buffered then.PARAM:If numeric: We assume it as assumed to be absolute byte size.If string : May end with one of the usual unit endings e.g 'k', 'kb', 'M' (kilo-, mega-byte)If ending with '%' this means use x % of the available memory as given bymemory_limit in the php.ini file. But we never exceed 80%.

Parameter
mixed $newBufSize
(see above)
Returns int

The set buffersize in byte.

Throws FALSE on error. (Buffer size is left unchanged)

setBufferLifetime

private void setBufferLifetime( [ integer $sec ] )

  The max time a memory buffered data is considered 'up to date' befor an 'up to date'-check
on the 'origin'-file is fired. Only active if there is an 'origin'-file in use.If the 'origin'-file has changed since a fetch() will return the 'out of date'-value NULL.(More doc in header).

Parameter
integer $sec = >>10<<
(default is 10s)
Returns void

See Also setCacheLifeTime()

setCacheLifeTime

private void setCacheLifeTime( [ integer $sec ] )

  The max time until the cached data is considered 'out to date' even if the 'origin'-file
hasn't changed. After this time a fetch() will return the 'out of date'-value NULL.Use if you want to limit the chache lifetime or when there is no 'origin'-file tocheck against (More doc in header).

Parameter
integer $sec = >>0<<
(default is 0 == 'no lifetime check'). See above.
Returns void

See Also setBufferLifetime()

setDir

private void setDir( [ string $path ] )

  Define where you want the cache-files to be stored.
If a valid path is passed all cache-files are stored in that dir. if the path does notexist yet, this method tries to create it.If called without param (or the dir is not writeable or not createable or whatever) asubdir called '_cache' will be created below the 'origin-file' dir and the cache-filesare stored there (default behavior, fallback too).

Parameter
string $path = >>''<<
(see above).
Returns void


setVerboseCacheNames

private void setVerboseCacheNames( [ string $trueFalse ] )

  Define if the 'cache-files' should contain a verbose name or not.
A verbose name contains the name of the 'origin-file' up to 100 chars.To keep the file unique, a md5-string is always appended to the chach-file.( The full path is taken to built the md5-string)

Parameter
string $trueFalse = >>TRUE<<
(see above).
Returns void


getLastError

private mixed getLastError( )

  Get last error.

Returns mixed

If last public fuction had an error, a string is returned otherwise FALSE.


_getFiFoIndex

private int _getFiFoIndex( $filePath )

  Find the index of the fifo-array matching $filePath

Parameter
$filePath
Warning: documentation is missing.
Returns int

The index (see above)

Throws FALSE if not found.

_addToFiFo

private bool _addToFiFo( array $cacheBlock )

  Add $cacheBlock to fifo-array

Parameter
array $cacheBlock
A data chunck
Returns bool

TRUE if add succeded, otherwise FALSE


_fifoFreeSpace

private void _fifoFreeSpace( $sizeOfNewData )

  Free up the fifo-array until $sizeOfNewData fits in.

Parameter
$sizeOfNewData
Warning: documentation is missing.
Returns void


_fifoGarbageCollect

private void _fifoGarbageCollect( )

  Get rid of entries in the fifo-array that are marked invalid

Returns void


_determinePathToCache

private void _determinePathToCache( $filePath )

  Determine the cache-dir from the origin-dir and make the cache name.
Problems solved here:a) If 'verboseName' is TRUE then include the origin-name into the cache name.b) If 'storeDir' is set all cache-files are stored in one dir and have to be unique.c) Unique file names are achieved by appending a md5-stringMake unique name with md5(abs.path/origin-file)

Parameter
$filePath
Warning: documentation is missing.
Returns void


_isCacheFileUptodate

private bool _isCacheFileUptodate( $filePath, $cacheFilePath )

  'Up To Date' - checking:
It is assumed that the passed 'data stream' has it's origin in data file thatwas crunched (or parsed or whatever) and that the cache is valid as long asthe 'origin-file' exits and is not modified.An 'Up To Date'-check compars the mod-time of the 'origin-file' against themod time of the 'cache-file'. If'origin-file-time' <= 'cache-file-time'the cache is consitered 'up to date'.The 'Up To Date' check takes place every time the 'cache-file' has to be loadedinto the memory buffer.

Parameter
$filePath
Warning: documentation is missing.
$cacheFilePath
Warning: documentation is missing.
Returns bool

TRUE on success. FALSE Otherwise.

Throws FALSE on all errors. Check getLastError().

_writeCacheFile

private void _writeCacheFile( $cacheFilePath, $cacheBlock )

  Write cache

Parameter
$cacheFilePath
Warning: documentation is missing.
$cacheBlock
Warning: documentation is missing.
Returns void

Throws FALSE on all errors. Check getLastError().

_readCacheFile

private void _readCacheFile( $cacheFilePath )

  Read cache

Parameter
$cacheFilePath
Warning: documentation is missing.
Returns void

Throws FALSE on all errors. Check getLastError().

Private Field Details

$_bsFile

private object [unknown] $_bsFile

>><<

STATIC instance of Bs_File. gets instanced the first time in _writeCacheFile().


$_cacheProp

private array $_cacheProp

>>array( 'maxCacheLifeTime' => 0, // <= Time (in secs<<

Internal cache properties

See Also setVerboseCacheNames()

$_fifoBuffer

private array $_fifoBuffer

>>array()<<

The second level cache as fifo list.


$_cacheVersion

private string $_cacheVersion

>>NULL<<

The cache data has a version to identify outdated/invalid cache data.
*All* cache with older versions are then 'out of date'. Very usefull during developmentand updates, where stucture of data you generate (and cache) has changed. Saves youthe hassel to go an delete all old cache files spread all over the disk.Use an int and increase it on every structure change. Set it in the constructor.


$_lastErrMsg

private string $_lastErrMsg

>>''<<

contains the last error that occured and *is* reset after every *successfull* public function call.

See Also $_errMsgHistory

$_errMsgHistory

private array $_errMsgHistory

>>array()<<

for debugging. contains an error history that is *not* reset.

See Also $_errMsgHistory

$_determineFileNameHash

private array $_determineFileNameHash

>>array()<<



Private Constant Details

Bs_FILECACHE_VERSION

define( Bs_FILECACHE_VERSION, >>4.0.$x$<< )
Case: default: case sensitive




Packageindex Classtrees Modulegroups Elementlist Report XML Files
PHPDoc 1.0beta