PHP cache implementation code and detailed comments

Source: Internet
Author: User
Tags apc delete cache

CopyCode The Code is as follows: Class cacheexception extends exception {}
/**
* Cache abstract class
*/
Abstract class cache_abstract {
/**
* Read cache Variables
*
* @ Param string $ key cache subscript
* @ Return mixed
*/
Abstract Public Function fetch ($ key );

/**
* Cache Variables
*
* @ Param string $ key: cache variable subscript
* @ Param string $ value the cached variable value
* @ Return bool
*/
Abstract Public Function store ($ key, $ value );

/**
* Delete cache Variables
*
* @ Param string $ key cache subscript
* @ Return cache_abstract
*/
Abstract Public Function Delete ($ key );

/**
* Clear (delete) All caches
*
* @ Return cache_abstract
*/
Abstract Public Function clear ();

/**
* Lock cache Variables
*
* @ Param string $ key cache subscript
* @ Return cache_abstract
*/
Abstract Public Function lock ($ key );
/**
* Unlock cache Variables
*
* @ Param string $ key cache subscript
* @ Return cache_abstract
*/
Abstract Public Function unlock ($ key );
/**
* Whether the cache variable is locked
*
* @ Param string $ key cache subscript
* @ Return bool
*/
Abstract Public Function islocked ($ key );
/**
* Make sure that the instance is not locked.
* You can perform a maximum of $ tries sleep waiting for unlocking. If the time-out period expires, the system skips and unlocks the tries.
*
* @ Param string $ key cache subscript
*/
Public Function checklock ($ key ){
If (! $ This-> islocked ($ key )){
Return $ this;
}

$ Tries = 10;
$ COUNT = 0;
Do {
Usleep (200 );
$ Count ++;
} While ($ count <= $ tries & $ this-> islocked ($ key); // you can perform a maximum of ten sleep tasks and wait for unlocking. If the time-out period is exceeded and unlocked
$ This-> islocked ($ key) & $ this-> unlock ($ key );

Return $ this;
}
}

/**
* APC extension cache implementation
*
*
* @ Category mjie
* @ Package cache
* @ Author streamline Meng Chun
* @ Copyright (c) 2008-<cmpan (AT) QQ.com>
* @ License new BSD license
* @ Version $ ID: Cache/APC. php version 2010-04-18 cmpan $
*/
Class cache_apc extends cache_abstract {

Protected $ _ prefix = 'cache .mjie.net ';

Public Function _ construct (){
If (! Function_exists ('apc _ cache_info ')){
Throw new cacheexception ('apc extension didn \'t installed ');
}
}

/**
* Save cache Variables
*
* @ Param string $ key
* @ Param mixed $ Value
* @ Return bool
*/
Public Function store ($ key, $ value ){
Return apc_store ($ this-> _ storagekey ($ Key), $ value );
}

/**
* Read Cache
*
* @ Param string $ key
* @ Return mixed
*/
Public Function fetch ($ key ){
Return apc_fetch ($ this-> _ storagekey ($ key ));
}

/**
* Clear Cache
*
* @ Return cache_apc
*/
Public Function clear (){
Apc_clear_cache ();
Return $ this;
}

/**
* Delete A cache unit
*
* @ Return cache_apc
*/
Public Function Delete ($ key ){
Apc_delete ($ this-> _ storagekey ($ key ));
Return $ this;
}

/**
* Whether the cache unit is locked
*
* @ Param string $ key
* @ Return bool
*/
Public Function islocked ($ key ){
If (apc_fetch ($ this-> _ storagekey ($ key). '. lock') == false ){
Return false;
}

Return true;
}

/**
* Lock the cache unit
*
* @ Param string $ key
* @ Return cache_apc
*/
Public Function lock ($ key ){
Apc_store ($ this-> _ storagekey ($ key). '. lock', '', 5 );
Return $ this;
}

/**
* Cache unit unlocking
*
* @ Param string $ key
* @ Return cache_apc
*/
Public Function unlock ($ key ){
Apc_delete ($ this-> _ storagekey ($ key). '. lock ');
Return $ this;
}

/**
* Complete cache name
*
* @ Param string $ key
* @ Return string
*/
Private function _ storagekey ($ key ){
Return $ this-> _ prefix. '_'. $ key;
}
}
/**
* File Cache implementation
*
*
* @ Category mjie
* @ Package cache
* @ Author streamline Meng Chun
* @ Copyright (c) 2008-<cmpan (AT) QQ.com>
* @ License new BSD license
* @ Version $ ID: Cache/file. php version cmpan $
*/
Class cache_file extends cache_abstract {

Protected $ _ cachesdir = 'cache ';

Public Function _ construct (){
If (defined ('data _ dir ')){
$ This-> _ setcachedir (data_dir. '/cache ');
}
}

/**
* Getting cached files
*
* @ Param string $ key
* @ Return string
*/
Protected function _ getcachefile ($ key ){
Return $ this-> _ cachesdir. '/'. substr ($ key, 0, 2). '/'. $ key. '. php ';
}
/**
* Read cache Variables
* To prevent information leakage, the cached file is in the PHP file format and uses "<? PHP exit;?> Start"
*
* @ Param string $ key cache subscript
* @ Return mixed
*/
Public Function fetch ($ key ){
$ Cachefile = self: _ getcachefile ($ key );
If (file_exists ($ cachefile) & is_readable ($ cachefile )){
Return unserialize (@ file_get_contents ($ cachefile, false, null, 13 ));
}
Return false;
}
/**
* Cache Variables
* To prevent information leakage, the cached file is in the PHP file format and uses "<? PHP exit;?> Start"
*
* @ Param string $ key: cache variable subscript
* @ Param string $ value the cached variable value
* @ Return bool
*/
Public Function store ($ key, $ value ){
$ Cachefile = self: _ getcachefile ($ key );
$ Cachedir = dirname ($ cachefile );
If (! Is_dir ($ cachedir )){
If (mkdir ($ cachedir "target =" _ blank ">! @ Mkdir ($ cachedir, 0755, true )){
Throw new cacheexception ("cocould not make cache directory ");
}
}
Return @ file_put_contents ($ cachefile, '<? PHP exit;?> '. Serialize ($ value ));
}
/**
* Delete cache Variables
*
* @ Param string $ key cache subscript
* @ Return cache_file
*/
Public Function Delete ($ key ){
If (emptyempty ($ key )){
Throw new cacheexception ("missing argument 1 for cache_file: delete ()");
}

$ cachefile = self: _ getcachefile ($ key);
if ($ cachefile "target =" _ blank ">! @ Unlink ($ cachefile) {
throw new cacheexception ("cache file cocould not be deleted");
}< br> return $ this;
}< br>/**
* Whether the cache unit is locked
* @ Param string $ key
* @ return bool
*/
Public Function islocked ($ key) {
$ cachefile = self: _ getcachefile ($ key);
clearstatcache ();
return file_exists ($ cachefile. '. lock');
}< br>/**
* locked
* @ Param string $ Ke Y
* @ return cache_file
*/
Public Function lock ($ key) {
$ cachefile = self: _ getcachefile ($ key );
$ cachedir = dirname ($ cachefile);
If (! Is_dir ($ cachedir) {
If (mkdir ($ cachedir "target =" _ blank ">! @ Mkdir ($ cachedir, 0755, true) {
If (! Is_dir ($ cachedir) {
throw new cacheexception ("cocould not make cache directory ");
}< BR >}< br> // set the access and modification time of the cache lock file
@ touch ($ cachefile. '. lock');
return $ this;
}

/**
* Unlock
*
* @ Param string $ key
* @ Return cache_file
*/
Public Function unlock ($ key ){
$ Cachefile = self: _ getcachefile ($ key );
@ Unlink ($ cachefile. '. lock ');
Return $ this;
}
/**
* Set the file cache directory
* @ Param string $ dir
* @ Return cache_file
*/
Protected function _ setcachedir ($ DIR ){
$ This-> _ cachesdir = rtrim (str_replace ('\', '/', trim ($ DIR )),'/');
Clearstatcache ();
If (! Is_dir ($ this-> _ cachesdir )){
Mkdir ($ this-> _ cachesdir, 0755, true );
}
//
Return $ this;
}

/**
* Clear all caches
*
* @ Return cache_file
*/
Public Function clear (){
// Clear the cache by traversing the Directory
$ Cachedir = $ this-> _ cachesdir;
$ D = Dir ($ cachedir );
While (false! ==( $ Entry = $ D-> Read ())){
If ('.' = $ entry [0]) {
Continue;
}

$ Cacheentry = $ cachedir. '/'. $ entry;
If (is_file ($ cacheentry )){
@ Unlink ($ cacheentry );
} Elseif (is_dir ($ cacheentry )){
// The cache folder has two levels
$ D2 = Dir ($ cacheentry );
While (false! ==( $ Entry = $ D2-> Read ())){
If ('.' = $ entry [0]) {
Continue;
}

$ Cacheentry. = '/'. $ entry;
If (is_file ($ cacheentry )){
@ Unlink ($ cacheentry );
}
}
$ D2-> close ();
}
}
$ D-> close ();

Return $ this;
}
}
/**
* Data Structure of the cache unit
* Array (
* 'Time' => time (), // The timestamp when the cache is written.
* 'Expire '=> $ expire, // cache expiration time
* 'Valid' => true, // whether the cache is valid
* 'Data' => $ value // cached Value
*);
*/
Final class cache {
/**
* Cache expiration time (s)
*
* @ Var int
*/
Private $ _ expire = 3600;
/**
* Cache Processing
*
* @ Var cache_abstract
*/
Private $ _ storage = NULL;
/**
* @ Return Cache
*/
Static public function createcache ($ cacheclass = 'cache _ file '){
Return New Self ($ cacheclass );
}
Private function _ construct ($ cacheclass ){
$ This-> _ storage = new $ cacheclass ();
}
/**
* Set Cache
*
* @ Param string $ key
* @ Param mixed $ Value
* @ Param int $ expire
*/
Public Function set ($ key, $ value, $ expire = false ){
If (! $ Expire ){
$ Expire = $ this-> _ expire;
}

$ This-> _ storage-> checklock ($ key );

$ DATA = array ('time' => time (), 'expire '=> $ expire, 'valid' => true, 'data' => $ value );
$ This-> _ storage-> lock ($ key );

Try {
$ This-> _ storage-> store ($ key, $ data );
$ This-> _ storage-> unlock ($ key );
} Catch (cacheexception $ e ){
$ This-> _ storage-> unlock ($ key );
Throw $ E;
}
}
/**
* Read Cache
*
* @ Param string $ key
* @ Return mixed
*/
Public Function get ($ key ){
$ DATA = $ this-> fetch ($ key );
If ($ Data & $ data ['valid'] &! $ Data ['isexpired']) {
Return $ data ['data'];
}

Return false;
}
/**
* Read cache, including expired and invalid, to obtain the complete Storage Structure
*
* @ Param string $ key
*/
Public Function fetch ($ key ){
$ This-> _ storage-> checklock ($ key );
$ DATA = $ this-> _ storage-> fetch ($ key );
If ($ data ){
$ Data ['isexpired'] = (Time ()-$ data ['time'])> $ data ['expire ']? True: false;
Return $ data;
}

Return false;
}
/**
* Delete Cache
*
* @ Param string $ key
*/
Public Function Delete ($ key ){
$ This-> _ storage-> checklock ($ key)
-> Lock ($ key)
-> Delete ($ key)
-> Unlock ($ key );
}

Public Function clear (){
$ This-> _ storage-> clear ();
}
/**
* Set the cache to invalid
*
* @ Param string $ key
*/
Public Function setinvalidate ($ key ){
$ This-> _ storage-> checklock ($ key)
-> Lock ($ key );
Try {
$ DATA = $ this-> _ storage-> fetch ($ key );
If ($ data ){
$ Data ['valid'] = false;
$ This-> _ storage-> store ($ key, $ data );
}
$ This-> _ storage-> unlock ($ key );
} Catch (cacheexception $ e ){
$ This-> _ storage-> unlock ($ key );
Throw $ E;
}
}

/**
* Set cache expiration time (s)
*
* @ Param int $ expire
*/
Public Function setexpire ($ expire ){
$ This-> _ expire = (INT) $ expire;
Return $ this;
}
}

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.