This library lists apc_*
family of functions for eAccelerator, xCache or Disk Cache operations if APC or APCu is not available on server. When APC is installed and enabled, this library does nothing (because the desired functions are already available) – resulting in zero wrapper call overhead since all calls go directly to internal APC api.
In simple words, whether or not your PHP installation has a caching engine, you can always use apc_store
, apc_fetch
and apc_delete
for your cache management.
This wrapper was written to abstract out or automate the cache engine selection. This wraps three basic read/write/delete functions of common caching engines and disk caching as well. I named all the functions after APC api so that whatever caching engine I have on my server, my application does not require a change, and in case my server has APC installed and enabled, I get the additional benefit of Zero overhead on internal function calls.
The Code
$apc_cache_dir = 'cache/data/'; if( !function_exists( 'apc_store' ) ) { if( function_exists( 'eaccelerator_put' ) ) { function apc_store( $k , $d , $t = 0 ) { return eaccelerator_put( $k , $d , $t ); } function apc_fetch( $k ) { return eaccelerator_get( $k ); } function apc_delete( $k ) { return eaccelerator_rm( $k ); } } else if( function_exists( 'xcache_set' ) ) { function apc_store( $k , $d , $t = 0 ) { return xcache_set( $k , $d , $t ); } function apc_fetch( $k ) { return xcache_get( $k ); } function apc_delete( $k ) { return xcache_unset( $k ); } } else { function apc_store( $k , $d , $t = 0 ) { $to_file = $GLOBALS['apc_cache_dir'] . md5( $k ); if( touch( $to_file ) && is_writable( $to_file ) ) { return ( bool ) file_put_contents( $to_file , serialize( $d ) ); } return false; } function apc_fetch( $k ) { $from_file = $GLOBALS['apc_cache_dir'] . md5( $k ); if( file_exists( $from_file ) ) { return unserialize( file_get_contents( $from_file ) ); } return false; } function apc_delete( $k ) { $to_file = $GLOBALS['apc_cache_dir'] . md5( $k ); if( file_exists( $to_file ) && is_writable( $to_file ) ) { return unlink( $to_file ); } return false; } } }
Installation & Configuration
Save the code as apc.php
and include in your script. You have to define a valid cache path for Disk Caching.
include( $base . 'lib/apc.php' ); //Setting disk cache path $apc_cache_dir = $app_base . '/cache/data/';
Additionally, you would have to set appropriate permissions for your cache directory $apc_cache_dir
to make it writable.
Storing, Fetching & Deleting Key-Value Pairs
// $key = 'app::entry::' . $entry_id; // $value = $obj->get_entry( $entry_id ); //$value will be stored through the best available among APC, eAccelerator, xCache & Disk apc_store( $key , $value , $ttl = 0 ); //$value1 is now same as $value $value1 = apc_fetch( $key ); apc_delete( $key );