PHP file data cache implementation code_PHP tutorial

WBOY
Release: 2016-07-20 11:09:03
Original
990 people have browsed it

PHP implements file data caching to implement code caching technology. Every time a page is accessed, it will first detect whether the corresponding cache exists. If it does not exist, connect to the database, obtain the data, complete the assignment of template variables, display the page, and generate cache files at the same time. , so that the cached file will play a role the next time you visit

PHP tutorial to implement file data caching implementation code
Caching technology is that every time you visit a page, it will first detect whether the corresponding cache exists. If it does not exist, Just connect to the database tutorial, get the data, complete the assignment of template variables, display the page, and generate a cache file at the same time, so that the cache file will take effect the next time you access it, and the data query statement of the if block will not be executed. Of course, there are many things to consider in actual use, such as validity period settings, cache group settings, etc.

class cacheexception extends exception {} 
/**
* Cache abstract class
*/ 
abstract class cache_abstract { 
    /**
* Read cache variable
*
* @param string $key cache subscript
* @return mixed
*/ 
    abstract public function fetch($key); 
     
    /**
* Cache variable
*
* @param string $key cache variable subscript
* @param string $value cache variable value
* @return bool
*/ 
    abstract public function store($key, $value); 
     
    /**
* Delete cache variable
*
* @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 variable
*
* @param string $key cache subscript
* @return cache_abstract
*/ 
    abstract public function lock($key); 
 
    /**
* Unlock cache variable
*
* @param string $key cache subscript
* @return cache_abstract
*/ 
    abstract public function unlock($key); 
 
    /**
* Get whether the cache variable is locked
*
* @param string $key cache subscript
* @return bool
*/ 
    abstract public function islocked($key); 
 
    /**
* Make sure it is not locked
* Sleep at most $tries times to wait for unlocking, skip and unlock after timeout
*
* @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));  // 最多做十次睡眠等待解锁,超时则跳过并解锁 
 
        $this->islocked($key) && $this->unlock($key); 
         
        return $this; 
    } 

 
 
/**
* apc extended cache implementation
*
*
* @category mjie
* @package cache
* @author Liushui Mengchun
* @copyright copyright (c) 2008-
* @license new bsd license
* @version $id: cache/apc.php version number 2010-04-18 23:02 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 variable
* *
* @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 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 cache unit
*
* @param string $key
* @return cache_apc
*/ 
    public function lock($key) { 
        apc_store($this->_storagekey($key) . '.lock', '', 5); 
        return $this; 
    } 
     
    /**
* Unlock cache unit
*
* @param string $key
* @return cache_apc
*/ 
    public function unlock($key) { 
        apc_delete($this->_storagekey($key) . '.lock'); 
        return $this; 
    } 
     
    /**
* Full cache name
*
* @param string $key
* @return string
*/ 
    private function _storagekey($key) { 
        return $this->_prefix . '_' . $key; 
    } 

 
/**
 * 文件缓存实现
 * 
 * 
 * @category   mjie
 * @package    cache
 * @author     流水孟春
 * @copyright  copyright (c) 2008-
 * @license    new bsd license
 * @version    $id: cache/file.php 版本号 2010-04-18 16:46 cmpan $
 */ 
class cache_file extends cache_abstract { 
    public $usesubdir     = false; 
     
    protected $_cachesdir = 'cache'; 
     
    public function __construct() { 
        if (defined('data_dir')) { 
            $this->_setcachedir(data_dir . '/cache'); 
        } 
    } 
     
    /**
* Get cache file
*
* @param string $key
* @return string
*/ 
    protected function _getcachefile($key) { 
        $subdir = $this->usesubdir ? substr($key, 0, 2) . '/' : ''; 
        return $this->_cachesdir . '/' . $subdir . $key . '.php'; 
    } 
 
    /**
* Read cache variables
* To prevent information leakage, the cache file format is a php file and starts with ""
*
* @param string $ key cache subscript
* @return mixed
*/ 
    public function fetch($key) { 
        $cachefile = self::_getcachefile($key); 
        if (file_exists($cachefile) && is_readable($cachefile)) { 
            // include 方式 
            //return include $cachefile; 
            // 系列化方式 
 
            return unserialize(@file_get_contents($cachefile, false, null, 13)); 
        } 
 
        return false; 
    } 
 
    /**
* Cache variable
* To prevent information leakage, the cache file format is a php file and starts with ""
*
* @param string $key cache Variable subscript
* @param string $value The value of the cache variable
* @return bool
*/ 
    public function store($key, $value) { 
        $cachefile = self::_getcachefile($key); 
        $cachedir  = dirname($cachefile); 
 
        if(!is_dir($cachedir)) { 
            if(!@mkdir($cachedir, 0755, true)) { 
                throw new cacheexception("could not make cache directory"); 
            } 
        } 
    // 用include方式 
        //return @file_put_contents($cachefile, ' 
        return @file_put_contents($cachefile, '' . serialize($value)); 
    } 
 
    /**
     * 删除缓存变量
     *
     * @param string $key 缓存下标
     * @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(!@unlink($cachefile)) { 
            throw new cacheexception("cache file could not be deleted"); 
        } 
 
        return $this; 
    } 
 
    /**
* Whether the cache unit has been locked
*
* @param string $key
* @return bool
*/ 
    public function islocked($key) { 
        $cachefile = self::_getcachefile($key); 
        clearstatcache(); 
        return file_exists($cachefile . '.lock'); 
    } 
 
    /**
     * 锁定
     *
     * @param string $key
     * @return cache_file
    */ 
    public function lock($key) { 
        $cachefile = self::_getcachefile($key); 
        $cachedir  = dirname($cachefile); 
        if(!is_dir($cachedir)) { 
            if(!@mkdir($cachedir, 0755, true)) { 
                if(!is_dir($cachedir)) { 
                    throw new cacheexception("could not make cache directory"); 
                } 
            } 
        } 
 
        // 设定缓存锁文件的访问和修改时间 
        @touch($cachefile . '.lock'); 
        return $this; 
    } 
   
    /**
     * 解锁
     *
     * @param string $key
     * @return cache_file
    */ 
    public function unlock($key) { 
        $cachefile = self::_getcachefile($key); 
        @unlink($cachefile . '.lock'); 
        return 

下面来看一款关于smarty缓存的文件实例代码

再来看看smarty提供的页面缓存功能:

 

 1

  2require('smarty.class.php');

  3$smarty = new smarty;

  4$smarty->caching = true;

  5if(!$smarty->is_cached('index.tpl')) {

  6 // no cache available, do variable assignments here.

  7 $contents = get_database_contents();

  8 $smarty->assign($contents);

  9}

  10$smarty->display('index.tpl');

  11?>

php缓存技术工作时,当程序查询数据的时候,会把相应的结果序列化后保存到文件中,以后同样的查询语句就可以不用直接查询数据库,而是从缓存文件中获得。这一改进使得程序运行速度得以太幅度提升.

 


www.bkjia.comtruehttp: //www.bkjia.com/PHPjc/444824.htmlTechArticlephp implements file data caching and code caching technology. Every time a page is accessed, it will first detect whether the corresponding cache is Exists, if not, connect to the database and get the data,...
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template