PHP File Cache class Summary

Source: Internet
Author: User
Tags flock
This article mainly introduces the PHP File Cache class. The instance summarizes common File Cache classes and their usage, which is very useful. For more information, see

This article mainly introduces the PHP File Cache class. The instance summarizes common File Cache classes and their usage, which is very useful. For more information, see

This article describes the php File Cache class. Share it with you for your reference. The specific analysis is as follows:

The cache class is a common function used in our development and application. Below we will organize several PHP File Cache classes for you. Different File Cache classes are written differently, however, there will be differences in performance. If you are interested in testing, you can test these cache classes.

Example 1

The Code is as follows:

<? Php
$ Fzz = new fzz_cache;
$ Fzz-> kk = $ _ SERVER; // write Cache
// $ Fzz-> set ("kk", $ _ SERVER, 10000); // This method does not conflict with the class attribute. You can use any cache name;
Print_r ($ fzz-> kk); // read Cache
// Print_r ($ fzz-> get ("kk "));
// Unset ($ fzz-> kk); // deletes the cache
// $ Fzz-> _ unset ("kk ");
Var_dump (isset ($ fzz-> kk); // determines whether the cache exists.
// $ Fzz-> _ isset ("kk ");
// $ Fzz-> clear (); // clear the expired Cache
// $ Fzz-> clear_all (); // clear all cached files
Class fzz_cache {
Public $ limit_time = 20000; // cache expiration time
Public $ cache_dir = "data"; // cache file storage directory
// Write Cache
Function _ set ($ key, $ val ){
$ This-> _ set ($ key, $ val );
}
// The third parameter is the expiration time.
Function _ set ($ key, $ val, $ limit_time = null ){
$ Limit_time = $ limit_time? $ Limit_time: $ this-> limit_time;
$ File = $ this-> cache_dir. "/". $ key. ". cache ";
$ Val = serialize ($ val );
@ File_put_contents ($ file, $ val) or $ this-> error (_ line __, "fail to write in file ");
@ Chmod ($ file, 0777 );
@ Touch ($ file, time () + $ limit_time) or $ this-> error (_ line __, "fail to change time ");
}

// Read the cache
Function _ get ($ key ){
Return $ this-> _ get ($ key );
}
Function _ get ($ key ){
$ File = $ this-> cache_dir. "/". $ key. ". cache ";
If (@ filemtime ($ file)> = time ()){
Return unserialize (file_get_contents ($ file ));
} Else {
@ Unlink ($ file) or $ this-> error (_ line __, "fail to unlink ");
Return false;
}
}

// Delete the cached File
Function _ unset ($ key ){
Return $ this-> _ unset ($ key );
}
Function _ unset ($ key ){
If (@ unlink ($ this-> cache_dir. "/". $ key. ". cache ")){
Return true;
} Else {
Return false;
}
}

// Check whether the cache exists. If it expires, it is deemed that it does not exist.
Function _ isset ($ key ){
Return $ this-> _ isset ($ key );
}
Function _ isset ($ key ){
$ File = $ this-> cache_dir. "/". $ key. ". cache ";
If (@ filemtime ($ file)> = time ()){
Return true;
} Else {
@ Unlink ($ file );
Return false;
}
}

// Clear expired cache files
Function clear (){
$ Files = scandir ($ this-> cache_dir );
Foreach ($ files as $ val ){
If (filemtime ($ this-> cache_dir. "/". $ val) @ Unlink ($ this-> cache_dir. "/". $ val );
}
}
}

// Clear all cached files
Function clear_all (){
$ Files = scandir ($ this-> cache_dir );
Foreach ($ files as $ val ){
@ Unlink ($ this-> cache_dir. "/". $ val );
}
}

Function error ($ msg, $ debug = false ){
$ Err = new Exception ($ msg );
$ Str ="


error:
".print_r($err->getTrace(),1)."
";
If ($ debug = true ){
File_put_contents (date ('Y-m-d H_ I _s '). ". log", $ str );
Return $ str;
} Else {
Die ($ str );
}
}
}
?>

Example 2: the PHP File Cache class extracted from the stblog and the file_helper class of CI community, a simple file-based key-> value cache class.

This class can be used to cache some basic information, such as the blog header, footer, and sidebar, which is not frequently changed and retrieved from the database, before getting data, first determine whether the content in the File Cache has expired. If it has not expired, connect to the database for query and re-write the results to the File Cache to update the expiration time. It is similar to memcache, but it is more convenient. It is enough for some small applications.

The Code is as follows:

The Code is as follows:

<? Php
Define ('Directory _ secret ','/');
Define ('fopen _ write_create_destructive', 'wb ');
Define ('fopen _ WRITE_CREATE ',' AB ');
Define ('dir _ WRITE_MODE ', 0777 );
Class FileCache {
/**
* Cache path
*
* @ Access private
* @ Var string
*/
Private $ _ cache_path;
/**
* Cache expiration time, in seconds second
*
* @ Access private
* @ Var int
*/
Private $ _ cache_expire;

/**
* The parsing function sets cache expiration practices and storage paths.
*
* @ Access public
* @ Return void
*/
Public function _ construct ($ expire, $ cache_path)
{
$ This-> _ cache_expire = $ expire;
$ This-> _ cache_path = $ cache_path;
}

/**
* Cache file name
*
* @ Access public
* @ Param string $ key
* @ Return void
*/
Private function _ file ($ key)
{
Return $ this-> _ cache_path. md5 ($ key );
}

/**
* Set Cache
*
* @ Access public
* @ Param string $ unique key of the key Cache
* @ Param string $ data cached content
* @ Return bool
*/
Public function set ($ key, $ data)
{
$ Value = serialize ($ data );

$ File = $ this-> _ file ($ key );

Return $ this-> write_file ($ file, $ value );
}

/**
* Get Cache
*
* @ Access public
* @ Param string $ unique key of the key Cache
* @ Return mixed
*/
Public function get ($ key)
{
$ File = $ this-> _ file ($ key );

/** The file does not exist or the directory cannot be written */
If (! File_exists ($ file) |! $ This-> is_really_writable ($ file ))
{
Return false;
}

/** The cache has not expired and is still available */
If (time () <(filemtime ($ file) + $ this-> _ cache_expire ))
{

$ Data = $ this-> read_file ($ file );

If (FALSE! = $ Data)
{
Return unserialize ($ data );
}

Return FALSE;
}

/** Cache expiration, delete */
@ Unlink ($ file );
Return FALSE;
}

Function read_file ($ file)
{
If (! File_exists ($ file ))
{
Return FALSE;
}

If (function_exists ('file _ get_contents '))
{
Return file_get_contents ($ file );
}
If (! $ Fp = @ fopen ($ file, FOPEN_READ ))
{
Return FALSE;
}

Flock ($ fp, LOCK_SH); // Add a shared lock before reading

$ Data = '';
If (filesize ($ file)> 0)
{
$ Data = & fread ($ fp, filesize ($ file ));
}
Flock ($ fp, LOCK_UN); // release the lock
Fclose ($ fp );
Return $ data;
}

Function write_file ($ path, $ data, $ mode = FOPEN_WRITE_CREATE_DESTRUCTIVE)
{
If (! $ Fp = @ fopen ($ path, $ mode ))
{
Return FALSE;
}

Flock ($ fp, LOCK_EX );
Fwrite ($ fp, $ data );
Flock ($ fp, LOCK_UN );
Fclose ($ fp );

Return TRUE;
}
Function is_really_writable ($ file) // compatible with various platforms to determine whether a file has write permission
{
// If we're on a Unix server with safe_mode off we call is_writable
If (DIRECTORY_SEPARATOR = '/' AND @ ini_get ("safe_mode") = FALSE)
{
Return is_writable ($ file );
}

// For windows servers and safe_mode "on" installations we'll actually
// Write a file then read it. Bah...
If (is_dir ($ file ))
{
$ File = rtrim ($ file, '/'). '/'. md5 (rand (1,100 ));

If ($ fp = @ fopen ($ file, FOPEN_WRITE_CREATE) === FALSE)
{
Return FALSE;
}

Fclose ($ fp );
@ Chmod ($ file, DIR_WRITE_MODE );
@ Unlink ($ file );
Return TRUE;
}
Elseif ($ fp = @ fopen ($ file, FOPEN_WRITE_CREATE) === FALSE)
{
Return FALSE;
}

Fclose ($ fp );
Return TRUE;
}
}
$ Cache = new FileCache (30, 'cache /');
$ Cache-> set ('test', 'This is a test .');
Print $ cache-> get ('test ');
/* End of file FlieCache. php */



Example 3. php file cache that I think is useful

The Code is as follows:

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.