| core_file

# Class: Bs_FileCache Source Location: /core/file/Bs_FileCache.class.php
### Class Overview
    Bs_Object
       |
       --Bs_FileCache
File Cache Class. #### Author(s): andrej arn <at blueshoes dot org>, Sam Blum <sam at blueshoes dot org> #### Version: 4.3.$Revision: 1.4 $ $Date: 2003/12/27 16:05:36 $ #### Copyright: blueshoes.org | ### Variables $_determineFileNameHash | ### Methods Bs_FileCache clearBuffer fetch flushFileCache getLastModified isModifiedSince setBufferLifetime setBufferSize setCacheLifeTime setDir setVerboseCacheNames store _addToFiFo _determinePathToCache _fifoFreeSpace _fifoGarbageCollect _getFiFoIndex _isCacheFileUptodate _readCacheFile _writeCacheFile
### Inherited Variables | ### Inherited Methods #### Class: Bs_Object Bs_Object::Bs_Object() Bs_Object::getErrors() Basic error handling: Get *all* errors as string array from the global Bs_Error-error stack. Bs_Object::getLastError() Basic error handling: Get last error string from the global Bs_Error-error stack. Bs_Object::getLastErrors() Basic error handling: Get last errors string array from the global Bs_Error-error stack sinc last call of getLastErrors(). Bs_Object::persist() Persists this object by serializing it and saving it to a file with unique name. Bs_Object::setError() Basic error handling: Push an error string on the global Bs_Error-error stack. Bs_Object::toHtml() Dumps the content of this object to a string using PHP's var_dump(). Bs_Object::toString() Dumps the content of this object to a string using PHP's var_dump(). Bs_Object::unpersist() Fetches an object that was persisted with persist()
### Class Details [line 91] File Cache Class. Like a lot of other caches and still a little different. Typical Use : You have just crunched data typically from a file using a lot of CPU and want to persist the crunched data for later use. Also you want to be notified if the persisted data has become 'out of date' because the 'origin-file' has changed AND/OR the lifetime you have set has passed. - (This is also referred as "Hot Update"). 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 persistent media (a file). 'buffer': Is used to describe the data brought into memory as optimization to avoid reading from the file (second level cache). FEATURES : Checks if 'origin-file' has changed AND/OR the lifetime you have set has passed (cache then becomes 'out of date'). 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 you generate has changed and all cache data becomes invalid. Saves you the hassle to delete all old cache files spread all over the disk. Exclusive cache writing to disk. Second level memory buffer that holds the cache data in memory for reuse (Currently only until script ends). setBufferSize() : Ability to set the memory buffer size in bytes OR in % of the available script memory. setDir() : Define where you want the cache-files to be stored. 2 options a) In one central dir b) Below each 'origin-file' in a subdir. 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 60 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 removed until 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       |           Disk
       data 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 the passed 'data stream' has it's origin in a data file that was crunched (or parsed or whatever) and that the cache is valid as long as the 'origin-file' exists and is not modified. An 'Up To Date'-check compares the mod-time of the 'origin-file' against the mod-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 loaded into the memory buffer. examples: check the 2 examples in the example folder. also check the HOWTO. dependencies: Bs_Dir, Bs_File, Bs_UnitConverter #### Tags:
pattern: | singleton: (pseudostatic)
example: | example
example: | example
access: | public
since: | bs4.1
copyright: | blueshoes.org
version: | 4.3.$Revision: 1.4 $ $Date: 2003/12/27 16:05:36 $
author: | andrej arn <at blueshoes dot org>, Sam Blum <sam at blueshoes dot org>
[ Top ] ### Class Variables #### $_determineFileNameHash = array() [line 629]
Type: | mixed
[ Top ] ### Class Methods ### constructor Bs_FileCache [line 147]
`Bs_FileCache Bs_FileCache( [mixed $cacheVersion = 0])`
Constructor. NOTE to $cacheVersion use: *All* cache with older versions are considerd 'out of date'. Very usefull during development and updates, where the structure of the data you generate has changed and all cache data becomes invalid. Saves you the hassle to delete all old cache files spread all over the disk. #### Parameters:
mixed | $cacheVersion | sting or int. Cache data with other version is considered invalid.
[ Top ] ### method clearBuffer [line 370]
`TRUE 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) #### Tags:
return: | (always)
#### Parameters:
string | $filePath | the full path to the 'origin-file'.
[ Top ] ### method fetch [line 210]
`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. #### Tags:
return: | The cached data on success OR NULL if data is out of date.
throws: | FALSE on all errors. Check getLastError().
#### Parameters:
string | $filePath | the full path to the 'origin-file'.
[ Top ] ### method flushFileCache [line 388]
`void flushFileCache( )`
kills all cached file content. #### Tags:
access: | public
[ Top ] ### method getLastModified [line 185]
`int getLastModified( string $filePath)`
#### Tags:
return: | (unix timestamp in GMT!!)
see: | Bs_FileCache::isModifiedSince()
throws: | bool FALSE if not cached.
access: | public
#### Parameters:
string | $filePath |
[ Top ] ### method isModifiedSince [line 168]
`bool isModifiedSince( string $filePath, int $since)`
#### Tags:
see: | Bs_FileCache::getLastModified()
access: | public
#### Parameters:
string | $filePath |
int | $since | (unix timestamp in GMT!!)
[ Top ] ### method setBufferLifetime [line 466]
`TRUE setBufferLifetime( [int $sec = 10])`
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). #### Tags:
return: | on success, FALSE otherwise
see: | save(), Bs_FileCache::setCacheLifeTime()
#### Parameters:
int | $sec | (default is 10s)
[ Top ] ### method setBufferSize [line 421]
`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 by memory_limit in the php.ini file. But we never exceed 80%. #### Tags:
return: | The set buffersize in byte.
throws: | FALSE on error. (Buffer size is left unchanged)
#### Parameters:
mixed | $newBufSize | (see above)
[ Top ] ### method setCacheLifeTime [line 483]
`TRUE setCacheLifeTime( [int $sec = 0])`
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 to check against (More doc in header). #### Tags:
return: | on success, FALSE otherwise
see: | save(), Bs_FileCache::setBufferLifetime()
#### Parameters:
int | $sec | (default is 0 == 'no lifetime check'). See above.
[ Top ] ### method setDir [line 502]
`TRUE 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 not exist yet, this method tries to create it. If called without param (or the dir is not writeable or not createable or whatever) a subdir called '_cache' will be created below the 'origin-file' dir and the cache-files are stored there (default behavior, fallback too). #### Tags:
return: | on success, FALSE otherwise
#### Parameters:
string | $path | (see above).
[ Top ] ### method setVerboseCacheNames [line 536]
`void setVerboseCacheNames( [bool $trueFalse = TRUE])`
Define if the 'cache-files' should contain a verbose name or not. A verbose name contains the name of the 'origin-file' up to 60 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) #### Parameters:
bool | $trueFalse | (see above).
[ Top ] ### method store [line 310]
`TRUE store( string $filePath, string $dataStream, [bool $originCheck = TRUE], [int $maxLifeTime = NULL])`
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 set to a int > 0. If not it will default to 24 houres. You can set a default $maxLifeTime with 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 or younger, cache is considered 'up to date' Why the need for a max lifetime? You may think "we can check if the original file 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 some calcuated data or something out of a database. 2) The origin data, may it come from a real file or not, may include a lifecycle. In my case the data is made up from an xml property file of a product in an eShop. Now that product may become alive or may become obsolete without that the original file changes, so that my crunching function comes up with a different result over time. #### Tags:
return: | on success. FALSE Otherwise.
see: | Bs_FileCache::setCacheLifeTime()
throws: | FALSE on all errors. Check getLastError().
#### Parameters:
string | $filePath | the full path to the 'origin-file'.
string | $dataStream | the data to store.
bool | $originCheck | (default: TRUE) If we should check if the origin has modified. If FALSE don't even assume an existing origin file.
int | $maxLifeTime | (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).
[ Top ] ### method _addToFiFo [line 564]
`bool _addToFiFo( array $cacheBlock)`
Add $cacheBlock to fifo-array #### Tags:
return: | TRUE if add succeded, otherwise FALSE
#### Parameters:
array | $cacheBlock | A data chunck
[ Top ] ### method _determinePathToCache [line 640]
`void _determinePathToCache( mixed $filePath)`
Determine the cache-dir from the origin-dir and makes 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-string Make unique name with md5(abs.path/origin-file) [ Top ] ### method _fifoFreeSpace [line 591]
`void _fifoFreeSpace( mixed $sizeOfNewData)`
Free up the fifo-array until $sizeOfNewData fits in. [ Top ] ### method _fifoGarbageCollect [line 609]
`void _fifoGarbageCollect( )`
Get rid of entries in the fifo-array that are marked invalid [ Top ] ### method _getFiFoIndex [line 550]
`int _getFiFoIndex( mixed $filePath)`
Find the index of the fifo-array matching $filePath #### Tags:
return: | The index (see above)
throws: | FALSE if not found.
[ Top ] ### method _isCacheFileUptodate [line 686]
`bool _isCacheFileUptodate( mixed $filePath, mixed $cacheFilePath)`
'Up To Date' - checking: It is assumed that the passed 'data stream' has it's origin in data file that was crunched (or parsed or whatever) and that the cache is valid as long as the 'origin-file' exits and is not modified. An 'Up To Date'-check compars the mod-time of the 'origin-file' against the mod 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 loaded into the memory buffer. #### Tags:
return: | TRUE if uptodate, FALSE if not AND NULL if an error occured (Check getLastError()).
[ Top ] ### method _readCacheFile [line 765]
`TRUE _readCacheFile( mixed $cacheFilePath)`
Read cache #### Tags:
return: | on success. FALSE Otherwise.
throws: | FALSE on all errors. See getLastError().
[ Top ] ### method _writeCacheFile [line 730]
`TRUE _writeCacheFile( mixed $cacheFilePath, mixed $cacheBlock)`
Write cache #### Tags:
return: | on success. FALSE Otherwise.
throws: | FALSE on all errors. Check getLastError().
[ Top ] Documentation generated on Mon, 29 Dec 2003 21:09:02 +0100 by phpDocumentor 1.2.3