Usage:
Memcached
$ Cache = new cache_memcache ();
$ Cache-> addserver ('www1 ');
$ Cache-> addserver ('www2 ', expires 11,20); // This server has double the memory, and gets double the weight
$ Cache-> addserver ('www3', 11211 );
// Store some data in the cache for 10 minutes
$ Cache-> store ('My _ key', 'foobar', 600 );
// Get It Out Of The cache again
Echo ($ cache-> fetch ('My _ key '));
File Cache
$ Cache = new cache_file ();
$ Key = 'getusers: selectall ';
// Check if the data is not in the cache already
If (! $ DATA = $ cache-> fetch ($ key )){
// Assuming there is a database connection
$ Result = mysql_query ("select * from users ");
$ DATA = array ();
// Fetching all the data and putting it in an array
While ($ ROW = mysql_fetch_assoc ($ result) {$ data [] = $ row ;}
// Storing the data in the cache for 10 minutes
$ Cache-> store ($ key, $ data, 600 );
}
Class_cache3.php
<? PHP
Abstract class cache_abstract {
Abstract function fetch ($ key );
Abstract function store ($ key, $ data, $ TTL );
Abstract function Delete ($ key );
}
Class cache_apc extends cache_abstract {
Function fetch ($ key ){
Return apc_fetch ($ key );
}
Function store ($ key, $ data, $ TTL ){
Return apc_store ($ key, $ data, $ TTL );
}
Function Delete ($ key ){
Return apc_delete ($ key );
}
}
Class cache_memcache extends cache_abstract {
Public $ connection;
Function _ construct (){
$ This-> connection = new memcache;
}
Function store ($ key, $ data, $ TTL ){
Return $ this-> connection-> set ($ key, $ data, 0, $ TTL );
}
Function fetch ($ key ){
Return $ this-> connection-> get ($ key );
}
Function Delete ($ key ){
Return $ this-> connection-> Delete ($ key );
}
Function addserver ($ host, $ Port = 11211, $ Weight = 10 ){
$ This-> connection-> addserver ($ host, $ port, true, $ weight );
}
}
Class cache_file extends cache_abstract {
Function store ($ key, $ data, $ TTL ){
$ H = fopen ($ this-> getfilename ($ Key), 'a + ');
If (! $ H)
Throw new exception ('could not write to cache ');
Flock ($ H, lock_ex );
Fseek ($ H, 0 );
Ftruncate ($ H, 0 );
$ DATA = serialize (array (Time () + $ TTL, $ data ));
If (fwrite ($ H, $ data) === false ){
Throw new exception ('could not write to cache ');
}
Fclose ($ H );
}
Function fetch ($ key ){
$ Filename = $ this-> getfilename ($ key );
If (! File_exists ($ filename ))
Return false;
$ H = fopen ($ filename, 'R ');
If (! $ H)
Return false;
Flock ($ H, lock_sh );
$ DATA = file_get_contents ($ filename );
Fclose ($ H );
$ DATA = @ unserialize ($ data );
If (! $ Data ){
Unlink ($ filename );
Return false;
}
If (Time ()> $ data [0]) {
Unlink ($ filename );
Return false;
}
Return $ data [1];
}
Function Delete ($ key ){
$ Filename = $ this-> getfilename ($ key );
If (file_exists ($ filename )){
Return unlink ($ filename );
}
Else {
Return false;
}
}
Private function getfilename ($ key ){
Return '/tmp/s_cache'. MD5 ($ key );
}
}
?>