I would like to share with you a PHP File Cache class, which is very practical. For more information, see.
The Code is as follows:
<? Php
/**
* @ Desc File Cache
*/
Class Cache {
Const C_FILE = '/Runtime /';
Private $ dir = '';
Const EXT = '. tpl ';
Private $ filename = '';
Public function _ construct ($ dir = ''){
$ This-> dir = $ dir;
}
/**
* @ Desc sets the File Cache
* @ Param string $ key file name
* @ Param unkonw $ data cache data
* @ Param int $ expire expiration time
*/
Public function set ($ key, $ data, $ expire = 0 ){
$ This-> filename = dirname (_ FILE _). self: C_FILE. $ this-> dir. $ key. self: EXT;
If (file_exists ($ this-> filename )){
$ Res = $ this-> get ($ key );
If (md5 ($ res) = md5 (json_encode ($ data ))){
Return true;
}
}
If (! Is_dir (dirname ($ this-> filename ))){
Mkdir (dirname ($ this-> filename), 0777 );
}
$ Source = fopen ($ this-> filename, 'W + ');
Fwrite ($ source, json_encode ($ data ));
Fclose ($ source );
}
/**
* @ Desc get the file
* @ Param string $ key file name
*/
Public function get ($ key ){
// $ Filename = dirname (_ FILE _). self: C_FILE. $ this-> dir. $ key. self: EXT;
If (! File_exists ($ this-> filename )){
Return 'cached file does not exist ';
} Else {
$ Res = file_get_contents ($ this-> filename );
}
Return $ res;
}
/**
* @ Desc delete an object
* @ Param string $ key file name
*/
Public function del ($ key ){
Unlink ($ this-> filename );
}
}
$ Data = array ('name' => 'song', 'age' => 20, 'sex' => 'man ', 'favority '=> array ('apple', 'bana '));
$ Cache = new Cache ();
$ Cache-> set ('cache', $ data );
// $ Cache-> get ('cache ');
// $ Cache-> del ('cache ');