Php File Cache class example sharing _ php instance

Source: Internet
Author: User
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 ');

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.