PHP file Caching Method Summary, _php tutorial

Source: Internet
Author: User
Tags flock glob php memcached rtrim

PHP file Caching Method Summary,


For everyone to share a very full PHP file cache, for your reference, the specific content as follows

<?php class cache{private static $_instance = null; protected $_options = Array (' cache_dir ' = './', ' File_nam   E_prefix ' + ' cache ', ' mode ' = ' 1 ',//mode 1 for Serialize Model 2 for Save as executable file; /** * Get this class instance * * @return ambiguous */public static function getinstance () {if (self::$_instance = = = null) {Self  :: $_instance = new self (); } return self::$_instance; /** * Get cached Information * * @param string $id * @return Boolean|array */public static function get ($id) {$instance = sel    F::getinstance ();  The 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; }/** * Set a cache * * @param string $id Cache ID * @param array $data cache contents * @param int $cacheLife cache life defaults to 0 infinite life */Publi    C 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); }/** * Clears a cache * * @param string Cache ID * @return void */public static function Delete ($id) {$instance = SE    Lf::getinstance ();  if (! $instance->has ($id)) {return false;  } $file = $instance->_file ($id); Delete the cache return unlink ($file); }/** * To determine if the cache exists * * @param string $id cache_id * @return Boolean true cache exists false cache does not exist */public static function H  As ($id) {$instance = Self::getinstance ();    $file = $instance->_file ($id);  if (!is_file ($file)) {return false; } return true; /** * Get cache information path by cache ID * @param string $id * @return String Cache file path */protected function _file ($id) {$instance = SE  Lf::getinstance ();  $fileNmae = $instance->_idtofilename ($id); return $instance->_options[' Cache_dir '] . $fileNmae; /** * Get cache information by ID store file name * * @param $id * @return String Cache file name */protected function _idtofilename ($id) {$instanc  E = Self::getinstance ();  $prefix = $instance->_options[' File_name_prefix '); Return $prefix. '---' . $id; /** * Gets the cache ID by fileName * * @param $id * @return string Cache ID */protected function _filenametoid ($fileName) {$in  Stance = Self::getinstance ();  $prefix = $instance->_options[' File_name_prefix '); Return preg_replace ('/^ '. $prefix. '---(. *) $/', ' $ ', $fileName); }/** * Writes data to file * * @param string $file file name * @param array $contents data contents * @return BOOL */protected function _  Fileputcontents ($file, $contents) {if ($this->_options[' mode '] = = 1) {$contents = serialize ($contents);    } else {$time = time ();     $contents = "<?php\n". "//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 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 cache Path * * @param string $path * @return Self */P  Ublic static function Setcachedir ($path) {$instance = Self::getinstance ();  if (!is_dir ($path)) {exit (' File_cache: '. $path. ' is not a valid path ');  } if (!is_writable ($path)) {exit (' File_cache: path '. $path. ' Not writable '); } $path = RTrim ($path, '/').  '/';    $instance->_options[' cache_dir ') = $path; return $instance; }/** * Set cache file Prefix * * @parAm srting $prefix * @return Self */public static function Setcacheprefix ($prefix) {$instance = Self::getinstance ();  $instance->_options[' file_name_prefix ') = $prefix; return $instance;  }/** * Set cache storage 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 sets the configuration information for the cache what the */cache::setcacheprefix (' core '); Set the cache file prefix Cache::setcachedir ('./cache '); Set the cache folder path//mode 1 Cache storage methodA: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 */* <?php//mktime:1318224645 return Array (' contents ' = = Array (0 = 1, 1 = 2, 2 = 3, 3 = 4 = 5, 5 = 6, 6 = 6,), ' expire ' = 0, ' mtime ' and 1318224645,?> * * */cache::setcachemod E (' 2 '); if (! $row = Cache::get (' zj2 ')) {$array = Array (1,2,3,34,5,6,6), $row = Cache::set (' zj2 ', $array);} Cache::flush (); Empty all Cache Print_r ($row);

File Cache class

<?php/** * File Cache class * @author Xiaojiong & 290747680@qq.com * @date 2011-08-17 */class cache{Const File_life_key = ' FI   Le_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 ' and 0777, ' file_life ' and ' 100000 '; static function &getinstance ($options = Array ()) {if (self::$_instance = = = null) {self::$_instance = new self ($op  tions); } return self::$_instance;   }/** * Set parameter * @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 ']. ' Not writable ';  }} else {exit (' File_cache: ' Options ' cache_dir cannot be empty '); }}/** * Set cache path * @param string $value * @return void */static function Setcachedir ($value) {$self = & self::     GetInstance ();  if (!is_dir ($value)) {exit (' File_cache: '. $value. ' is not a valid path ');  } if (!is_writable ($value)) {exit (' File_cache: path '. $value. ' Not writable '); } $value = RTrim ($this->_options[' Cache_dir '], '/').     '/'; $self->_options[' cache_dir ') = $value; }/** * Cache data * @param array $data put cached data * @param string $id Cache ID (aka cache identifier) * @param cache_life Cache time * @ret Urn Boolean True If no problem */static function Save ($data, $id = null, $cache _life = null) {$self = & Self::geti  Nstance ();   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 = "<?php\n". "//Mktime:". $time.    "\ n".    "Return".    Var_export ($data, True).     "\n?>";  $res = $self->_fileputcontents ($file, $data); return $res; /** * Get cached Information * * @param string $id Cache ID * @return String|array cache data */static function load ($id) {$self = &am P  Self::getinstance ();  $time = time ();   Detects if the cache exists if (! $self->test ($id)) {//The cache is not hit!  return false;     }//Clear all identification files $clearFile = $self->_file (self::clear_all_key);     $file = $self->_file ($id);  Determine if 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 Cache file * * @param string $file Cache path * @param string $string cache information * @return Boolean true Success */protected F  Unction _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 (including path) */protected function _file ($id) {$se  LF = & Self::getinstance ();  $fileName = $self->_idtofilename ($id); return $self->_options[' Cache_dir '). $fileName; }/** * Formatted cache file name * * @param string $id Cache ID * @return string cache filename  */protected function _idtofilename ($id) {$self = & Self::getinstance ();  $self->_id = $id;  $prefix = $self->_options[' File_name_prefix '); $result = $prefix. '---' .  $id; return $result; }/** * Determine if the cache exists * * @param string $id Cache ID * @return Boolean True cache exists False cache does not exist */static function test ($i  D) {$self = & Self::getinstance ();     $file = $self->_file ($id);  if (!is_file ($file)) {return false; } return true;  /** * Get cached Information * * @param string $file Cache path * @return String Cache Contents */protected function _filegetcontents ($file) {  if (!is_file ($file)) {return false; } return include $file;  }/** * Clears all caches * * @return void */static function clear () {$self = & Self::getinstance ();  $self->save (' Clear_all ', self::clear_all_key); }/** * Clears a cache * * @param string Cache ID * @return void */static function del ($id) {$self = & Self::get  Instance ();  if (! $self->test ($id)) {//The cache does not exist with return false;  }$file = $self->_file ($id); Return unlink ($file); } }

Deposit data

<?php$config = Array (' name ' = ' Xiaojiong ', ' qq ' = ' 290747680 ', ' age ' = ' 20 ',);//first parameter cache data//second parameter cache id// The third parameter, Cache_life 0, never Expires (Cache::clear () clears all except) by default Cache_life is Option_cache_lifecache::save ($config, ' config ', 0);

Loading data

<?php//only one parameter Cache_id$config = cache::load (' config ');

Empty cache

<?php//empty the specified cache::d El (' config ');//empties All cache Cache::clear ();

Cache information Configuration

Call $_options = Array (' cache_dir ' = './cache ',//cache file directory ' File_name_prefix ' + ' cache ',//buffer file prefix before executing all cache_func) File_life ' + 100000,//cache file life); Cache::setoptions ($options);//The execution will be performed according to the new configuration information, otherwise the default information Cache::save ($arr, ' arr ');/ This is the way it seems unreasonable to look at everyone pointing

The above is the whole content of this article, I hope that everyone's study has helped.

Articles you may be interested in:

    • PHP Memcached + APC + file cache encapsulation Implementation code
    • Performance test for PHP file cache
    • PHP File Cache function
    • How file cache to memory cache in PHP
    • PHP file cache Content Save Format instance analysis
    • PHP File Cache Class Summary
    • Common PHP Data File cache class summary
    • PHP File cache class sample sharing
    • Example Analysis of PHP file cache class Usage
    • thinkphp file cache class code sharing

http://www.bkjia.com/PHPjc/1111339.html www.bkjia.com true http://www.bkjia.com/PHPjc/1111339.html techarticle PHP File Cache method Summary, for everyone to share a very full PHP file cache, for your reference, the concrete content is as follows PHP class cache{private static $_instance = null; protected $_options...

  • 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.