php File Cache Class Summary

  • 2021-08-06 21:02:31
  • OfStack

This article describes the file cache class of php as an example. Share it for your reference. The specific analysis is as follows:

Cache class is a function commonly used in our development and application. Let's sort out several php file cache classes. Each file cache class is written differently, but there will be differences in performance. Friends who are interested in testing can test these cache classes under 1.

Example 1

<?php
$fzz = new fzz_cache;
$fzz->kk = $_SERVER; // Write cache
//$fzz->set("kk",$_SERVER,10000); // This method does not conflict with class attributes, and can use any cache name;
print_r($fzz->kk);  // Read cache
//print_r($fzz->get("kk"));
//unset($fzz->kk); // Delete cache
//$fzz->_unset("kk");
var_dump(isset($fzz->kk)); // Determine whether the cache exists
//$fzz->_isset("kk");
//$fzz->clear(); // Clean up the expired cache
//$fzz->clear_all(); // Clean up all cached files
class fzz_cache{
 public $limit_time = 20000; // Cache expiration time
 public $cache_dir = "data"; // Cache file saving directory
 // Write cache
 function __set($key , $val){
  $this->_set($key ,$val);
 }
 // No. 1 3 Parameters are 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 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 cache 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, and consider it nonexistent when it expires
 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)<time()){
    @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 = "<pre>
<span style='color:red'>error:</span>
".print_r($err->getTrace(),1)."
</pre>";
  if($debug == true) {
   file_put_contents(date('Y-m-d H_i_s').".log",$str);
   return $str;
  }else{
   die($str);
  }
 }
}
?>

Example 2. php file cache class extracted from stblog of CI community and file_helper class of CI, a simple file-based key- > value cache class.

This class can be used to cache 1 some basic information, such as blog header, footer, sidebar 1 not often change, take out the content from the database, take the data before judging whether the content in the file cache expired, if not expired out, expired then connect to the database query, and rewrite the results to the file cache, update the expiration time. Similar to memcache, but more convenient. It is enough for 1 small application.

The specific code is as follows

<?php
define('DIRECTORY_SEPARATOR','/');
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;
 
 /**
     * Resolve functions to set 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);
 }
 
 /**
     * Setting cache
     *
     * @access public
     * @param  string $key Cached only 1 Key
     * @param  string $data Cached contents
     * @return bool
     */
 public function set($key, $data)
 {
  $value = serialize($data);
 
  $file = $this->_file($key);
 
     return $this->write_file($file, $value);
 }
 
 /**
     * Get the cache
     *
     * @access public
     * @param  string $key Cached only 1 Key
     * @return mixed
     */
 public function get($key)
 {
  $file = $this->_file($key);
 
  /** File does not exist or directory is unwritable */
  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 expires, delete it */
  @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 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 all platforms to judge 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 very easy to use
<?php 
class cache
{
 private static $_instance = null;
    protected $_options = array(
        'cache_dir'        => "./",
        'file_name_prefix' => 'cache',
     'mode'            => '1', //mode 1 For serialize model 2 To save as an executable file
    );
 
 /**
  * Get an instance of this class
  *
  * @return Ambiguous
  */
 public static function getInstance()
 {
  if(self::$_instance === null)
  {
   self::$_instance = new self();
  }
  return self::$_instance;
 }
 
 /**
  * Get cache information
  *
  * @param string $id
  * @return boolean|array
  */
 public static function get($id)
 {
  $instance = self::getInstance();
 
  // Cache file does not exist
  if(!$instance->has($id))
  {
   return false;
  }
 
  $file = $instance->_file($id);
 
  $data = $instance->_fileGetContents($file);
 
  if($data['expire'] == 0 || time() < $data['expire'])
  {
   return $data['contents'];
  }
  return false;
 }
 
 /**
  * Settings 1 Cache
  *
  * @param string $id   Cache id
  * @param array  $data Cache content
  * @param int    $cacheLife Cache life Default to 0 Infinite life
  */
 public static function set($id, $data, $cacheLife = 0)
 {
  $instance = self::getInstance();
 
  $time = time();
  $cache      = array();
  $cache['contents'] = $data;
  $cache['expire']   = $cacheLife === 0 ? 0 : $time + $cacheLife;
  $cache['mtime']    = $time;
 
  $file = $instance->_file($id);
 
  return $instance->_filePutContents($file, $cache);
 }
 
    /**
     * Clear 1 Bar cache
     *
     * @param string cache id 
     * @return void
     */  
 public static function delete($id)
 {
  $instance = self::getInstance();
 
  if(!$instance->has($id))
  {
   return false;
  }
     $file = $instance->_file($id);
     // Delete the cache
     return unlink($file);
 }
 
 /**
  * Determine whether the cache exists
  *
  * @param string $id cache_id
  * @return boolean true Cache presence false Cache does not exist
  */
 public static function has($id)
 {
  $instance = self::getInstance();
  $file     = $instance->_file($id);
 
  if(!is_file($file))
  {
   return false;
  }
  return true;
 }
 
 /**
  * By caching id Get the cache information path
  * @param string $id
  * @return string Cache file path
  */
 protected function _file($id)
 {
  $instance  = self::getInstance();
  $fileNmae  = $instance->_idToFileName($id);
  return $instance->_options['cache_dir'] . $fileNmae;
 }
 
 /**
  * Pass id Get the file name of cache information storage
  *
  * @param  $id
  * @return string Cache file name
  */
 protected function _idToFileName($id)
 {
  $instance  = self::getInstance();
  $prefix    = $instance->_options['file_name_prefix'];
  return $prefix . '---' . $id;
 }
 
 /**
  * Pass filename Get the cache id
  *
  * @param  $id
  * @return string Cache id
  */
 protected function _fileNameToId($fileName)
 {
  $instance  = self::getInstance();
  $prefix    = $instance->_options['file_name_prefix'];
  return preg_replace('/^' . $prefix . '---(.*)$/', '$1', $fileName);
 }
 
 /**
  * Write data to a file
  *
  * @param string $file File name
  * @param array  $contents Data content
  * @return bool
  */
 protected function _filePutContents($file, $contents)
 {
  if($this->_options['mode'] == 1)
  {
   $contents = serialize($contents);
  }
  else
  {
   $time = time();
         $contents = "<?phpn".
                 " // mktime: ". $time. "n".
                 " return ".
                 var_export($contents, true).
                 "n?>";
  }
 
  $result = false;
     $f = @fopen($file, 'w');
        if ($f) {
            @flock($f, LOCK_EX);
            fseek($f, 0);
            ftruncate($f, 0);
            $tmp = @fwrite($f, $contents);
            if (!($tmp === false)) {
                $result = true;
            }
            @fclose($f);
        }
  @chmod($file,0777);
  return $result;   
 }
 
 /**
  * Get data from a file
  *
  * @param  sring $file
  * @return boolean|array
  */
 protected function _fileGetContents($file)
 {
  if(!is_file($file))
  {
   return false;
  }
 
  if($this->_options['mode'] == 1)
  {
   $f = @fopen($file, 'r');
   @$data = fread($f,filesize($file));
   @fclose($f);
   return unserialize($data);
  }
  else
  {
   return include $file;
  }
 }
 
 /**
  * Constructor
  */
 protected function __construct()
 {
 
 }
 
 /**
  * Set the cache path
  *
  * @param string $path
  * @return self
  */
 public static function setCacheDir($path)
 {
  $instance  = self::getInstance();
        if (!is_dir($path)) {
            exit('file_cache: ' . $path.' No 1 Valid paths ');
        }
        if (!is_writable($path)) {
            exit('file_cache: Path "'.$path.'" Unwritable ');
        }
   
        $path = rtrim($path,'/') . '/';
        $instance->_options['cache_dir'] = $path;
       
        return $instance;
 }
 
 /**
  * Set the cache file prefix
  *
  * @param srting $prefix
  * @return self
  */
 public static function setCachePrefix($prefix)
 {
  $instance  = self::getInstance();
  $instance->_options['file_name_prefix'] = $prefix;
  return $instance;
 }
 
 /**
  * Setting the cache store type
  *
  * @param int $mode
  * @return self
  */
 public static function setCacheMode($mode = 1)
 {
  $instance  = self::getInstance();
  if($mode == 1)
  {
   $instance->_options['mode'] = 1;
  }
  else
  {
   $instance->_options['mode'] = 2;
  }
 
  return $instance;
 }
 
 /**
  * Delete all caches
  * @return boolean
  */
 public static function flush()
 {
  $instance  = self::getInstance();
  $glob = @glob($instance->_options['cache_dir'] . $instance->_options['file_name_prefix'] . '--*');
 
  if(empty($glob))
  {
   return false;
  }
 
  foreach ($glob as $v)
  {
   $fileName = basename($v);
   $id =  $instance->_fileNameToId($fileName);
   $instance->delete($id);
  }
  return true;
 }
}
/* Initialization settings cache Configuration information of */
cache::setCachePrefix('core'); // Set the cache file prefix
cache::setCacheDir('./cache'); // Set the path to store the cache folder
// Mode 1 Cache storage mode
//a:3:{s:8:"contents";a:7:{i:0;i:1;i:1;i:2;i:2;i:3;i:3;i:34;i:4;i:5;i:5;i:6;i:6;i:6;}s:6:"expire";i:0;s:5:"mtime";i:1318218422;}
// Mode 2 Cache storage mode
/*
 <?php
 // mktime: 1318224645
 return array (
  'contents' =>
  array (
    0 => 1,
    1 => 2,
    2 => 3,
    3 => 34,
    4 => 5,
    5 => 6,
    6 => 6,
  ),
  'expire' => 0,
  'mtime' => 1318224645,
)
?>
 *
 *
 */
cache::setCacheMode('2');
if(!$row = cache::get('zj2'))
{
 
 $array = array(1,2,3,34,5,6,6);
 $row = cache::set('zj2',$array);
}
// cache::flush(); Empty all caches
print_r($row);


File cache class
<?php
/**
 * File cache class
 * @date 2011-08-17
 */
class cache
{
 const FILE_LIFE_KEY = 'FILE_LIFE_KEY';
 
 const CLEAR_ALL_KEY = 'CLEAR_ALL';
 
    static $_instance = null;
 
    protected $_options = array(
        'cache_dir' => './cache',
        'file_locking' => true,
        'file_name_prefix' => 'cache',
        'cache_file_umask' => 0777,
     'file_life'  => 100000
    );
   
    static function &getInstance($options = array())
    {
     if(self::$_instance === null)
     {
      self::$_instance = new self($options);
     }
     return self::$_instance;
    }
   
    /**
     * Setting parameters
     * @param  array $options Cache parameter
     * @return void
     */
 static function &setOptions($options = array())
 {
         return self::getInstance($options);
 }
 
    /**
     * Constructor
     * @param  array $options Cache parameter
     * @return void
     */
    private function __construct($options = array())
    { 
        if ($this->_options['cache_dir'] !== null) {
  
   $dir = rtrim($this->_options['cache_dir'],'/') . '/';
         $this->_options['cache_dir'] = $dir;
        
   if (!is_dir($this->_options['cache_dir'])) {
             mkdir($this->_options['cache_dir'],0777,TRUE);
         }
         if (!is_writable($this->_options['cache_dir'])) {
             exit('file_cache: Path "'. $this->_options['cache_dir'] .'" Unwritable ');
         }
     
        } else {
           exit('file_cache: "options" cache_dir Cannot be empty ');
        }
    }
    /**
     * Set the cache path
     * @param  string  $value
     * @return void
     */
    static function setCacheDir($value)
    {
     $self = & self::getInstance();
    
        if (!is_dir($value)) {
            exit('file_cache: ' . $value.' No 1 Valid paths ');
        }
        if (!is_writable($value)) {
            exit('file_cache: Path "'.$value.'" Unwritable ');
        }
   
        $value = rtrim($this->_options['cache_dir'],'/') . '/';
       
        $self->_options['cache_dir'] = $value;
    }
   
    /**
     * Data stored in cache
     * @param  array  $data          Data put into cache
     * @param  string $id            Cache id( Also known as cache identification code )
     * @param  cache_life            Cache time
     * @return boolean True if no problem
     */
    static function save($data, $id = null, $cache_life = null)
    {
     $self = & self::getInstance();
        if (!$id) {
            if ($self->_id) {
                $id = $self->_id;
            } else {
                exit('file_cache:save() id Cannot be empty !');
            }
        }
        $time = time();
       
        if($cache_life) {
         $data[self::FILE_LIFE_KEY] = $time + $cache_life;
        }
  elseif
  ($cache_life != 0){
         $data[self::FILE_LIFE_KEY] = $time + $self->_options['file_life'];
        }
       
        $file = $self->_file($id);
       
        $data = "<?phpn".
                " // mktime: ". $time. "n".
                " return ".
                var_export($data, true).
                "n?>"
                ;
       
        $res = $self->_filePutContents($file, $data);
        return $res;
    }
   
   
    /**
     * Get cache information
     *
     * @param  string  $id  Cache id
     * @return string|array Cache data
     */
    static function load($id)
    {
        $self = & self::getInstance();
     $time = time();
     // Detect whether the cache exists
     if (!$self->test($id)) {
            // The cache is not hit !
            return false;
        }
       
  // Empty all identification files
        $clearFile = $self->_file(self::CLEAR_ALL_KEY);
 
  $file = $self->_file($id);
 
        // Determine whether the cache has been completely cleared
     if(is_file($clearFile) && filemtime($clearFile) > filemtime($file))
     {
      return false;
     }
      
        $data = $self->_fileGetContents($file);
      if(empty($data[self::FILE_LIFE_KEY]) || $time < $data[self::FILE_LIFE_KEY]) {
            unset($data[self::FILE_LIFE_KEY]);
       return $data;  
      }
      return false;
    }   
   
    /**
     * Write to cache file
     *
     * @param  string $file   Cache path
     * @param  string $string Cache information
     * @return boolean true Success
     */
    protected function _filePutContents($file, $string)
    {
     $self = & self::getInstance();
        $result = false;
        $f = @fopen($file, 'ab+');
        if ($f) {
            if ($self->_options['file_locking']) @flock($f, LOCK_EX);
            fseek($f, 0);
            ftruncate($f, 0);
            $tmp = @fwrite($f, $string);
            if (!($tmp === false)) {
                $result = true;
            }
            @fclose($f);
        }
        @chmod($file, $self->_options['cache_file_umask']);
        return $result;
    }
   
    /**
     * Formatted cache file path
     *
     * @param  string $id Cache id
     * @return string Cache file name ( Include paths )
     */
    protected function _file($id)
    {
     $self = & self::getInstance();
        $fileName = $self->_idToFileName($id);
        return $self->_options['cache_dir'] . $fileName;
    }   
   
    /**
     * Formatted cache file name
     *
     * @param  string $id Cache id
     * @return string Cache file name
     */
    protected function _idToFileName($id)
    {
     $self = & self::getInstance();
        $self->_id = $id;
        $prefix = $self->_options['file_name_prefix'];
        $result = $prefix . '---' . $id;
        return $result;
    }  
   
    /**
     * Determine whether the cache exists
     *
     * @param  string $id Cache id
     * @return boolean True Cache presence False Cache does not exist
     */
    static function test($id)
    {
     $self = & self::getInstance();
        $file = $self->_file($id);
       
        if (!is_file($file)) {
            return false;
        }
       
        return true;
    }
   
    /**
     * Get cache information
     *
     * @param  string $file Cache path
     * @return string Cache content
     */
    protected function _fileGetContents($file)
    {
        if (!is_file($file)) {
            return false;
        }
        return include $file;
    }    
   
    /**
     * Clear all caches
     *
     * @return void
     */   
    static function clear()
    {
     $self = & self::getInstance();
     $self->save('CLEAR_ALL',self::CLEAR_ALL_KEY);
    }  
 
    /**
     * Clear 1 Bar cache
     *
     * @param string cache id 
     * @return void
     */  
    static function del($id)
    {
  $self = & self::getInstance();
     if(!$self->test($id)){
      // The cache does not exist
      return false;
     }
     $file = $self->_file($id);
     return unlink($file);
    }
}

Store data
<?php
$config = array(
 'name' => 'xiaojiong',
 'qq'   => '290747680',
 'age'  => '20',
);
// No. 1 1 Parameters Cache data
// No. 1 2 Parameters Cache id
// No. 1 3 Parameters cache_life 0 Never expire (cache::clear() Empty all except ) Default cache_life For option_cache_life
cache::save($config,'config',0);

Load data
<?php
// Only 1 Parameters cache_id
$config = cache::load('config');
Empty the cache
<?php
// Empty the specified cache
cache::del('config');
// Empty all caches
cache::clear();
cache Information configuration
// While executing all cache_func Pre-invocation
$_options = array(
    'cache_dir' => './cache', // Cache file directory
    'file_name_prefix' => 'cache',// Cache file prefix
    'file_life'  => 100000, // Cache file life
);
cache::setOptions($options);
// Re-execute It will be executed according to the new configuration information, otherwise it is the default information
cache::save($arr,'arr');

This method seems unreasonable, and interested friends can improve it. I hope this article is helpful to everyone's PHP programming.


Related articles: