PHP static File cache

Source: Internet
Author: User
Tags php compiler delete cache
PHP file cache is mainly used to alleviate the pressure of the database server, the said PHP file static cache refers to static, directly generate HTML or XML and other text files, there is an update when the re-generation, suitable for the less changing pages.

1. static file Caching
2.Memcache, Redis Cache
Static caching: Assemble the data in PHP and then write the data into the file.
staticcache.php

<?phpclass file{    Private $_dir;//defines a default path for    const EXT = '. txt ';//constants that define a filename suffix public    function __ Construct () {        $this->_dir = dirname (__file__). ' /files/';//Get the current directory of the file, put it in the Files folder under that directory, and assign to $_dir    }    //Generate/Delete cache three operations encapsulated in the CacheData method public    function CacheData ($key, $value = ', $path = ') {        $filename = $this->_dir. $path. self::ext;//assembled into one file: default directory, Path, file name, file name suffix        //write value value to cache        if ($value!== ") {        //delete cache            if (Is_null ($value)) {                return @unlink ($ filename);//unlink Delete file, @ Ignore warning            }            $dir = DirName ($filename);            if (!is_dir ($dir)) {//If the directory does not exist, create the directory first to get the directory            mkdir ($dir, 0777);        }        Return file_put_contents ($filename, Json_encode ($value));}        Gets the cache        if (!is_file ($filename)) {        return FALSE;        } else{            return Json_decode (file_get_contents ($filename), True);}}}    

test.php

<?phprequire_once ('./staticcache.php '); $data = array (' id ' = = 1, ' name ' = ' panda ', ' number ' = = Array (1,7,8)) ; $file = new file ();//Get Cache if ($file->cachedata (' Index_cache ')) {    var_dump ($file->cachedata (' Index_cache ') ); exit;    echo "Success";} else{    echo "error";}

After setting the static cache time optimization:
cachetime.php

<?phpclass file{Private $_dir;//defines a default path for const EXT = '. txt ';//A constant that defines a filename suffix public function __construct () { $this->_dir = dirname (__file__). ' /files/';//Get the current directory of the file, and then put it in the Files folder in that directory, then assign to $_dir}//The three operations of generate/Get/delete cache are encapsulated in the CacheData method in the Public function CacheData ($k EY, $value = ", $cacheTime = 0) {//CacheTime permanently valid $filename = $this->_dir. $key. self::ext;//assembled into one file: Default directory, path, filename, file Name suffix//write value value to cache if ($value!== ") {//delete cache if (Is_null ($value)) {return @unlink ($filename);//unlink Delete file, @ Ignore warning} $dir = DirName ($filename), if (!is_dir ($dir)) {//If the directory does not exist, create a directory, first get the directory mkdir ($dir, 0777);} $cacheTime = sprintf ('%011d ', $cacheTime)//specified cache time format, less than 11 bits, then 0, convenient to capture the return File_put_contents ($filename, $ Cachetime.json_encode ($value));//cache time and data stitching}//Get Cache if (!is_file ($filename)) {return FALSE;} $contents = file_get_contents ($filename); $cacheTime = (int) substr ($contents, 0,11); $value = substr ($contents, one); if ($ CacheTime!=0 && ($cacheTime + fileatime ($filename) <time())) {//To determine expiration unlink ($filename);//cache invalidation Delete file return FALSE;} Return Json_decode ($value, true);//If not expired, output cached content}}

Caching Mode Development Home interface

<?phprequire_once ('./jsonxml.php '); require_once ('./db.php '); require_once ('./cachetime.php '); $page = Isset ($_ get[' page '])? $_get[' page ': 1; $pageSize = isset ($_get[' pageSize ')? $_get[' pagesize ': 6;if (!is_numeric ($page) | |! Is_numeric ($pageSize)) {return response::show (401, ' data not valid ');} $offset = ($page-1) * $pageSize; $sql = "SELECT * from video where status = 1 ORDER BY: DESC limit". $offset. ",". $ PAGESIZE;//4-4 Read cache mode Development Home Interface $cache = new File (), $videos = Array (); if (! $videos = $cache->cachedata (' Index_yjp_cache '). $page. '-'. $pageSize)} {echo 1;exit;//if the cache fails output 1try{$connect = Db::getinstance ()->connect ();} catch (Exception $e) {return response::show (403, ' Database link failed ');} $result = mysql_query ($sql, $connect), $videos = Array (), while ($video = Mysql_fetch_assoc ($result)) {$videos [] = $video;} if ($videos) {$cache->cachedata (' Index_yjp_cache '. $page. '-'. $pageSize, $videos, 1200);}} if ($videos) {return response::show (200, ' Home data acquisition success ', $videos);} Else{return response::show (400, ' failure ', $videos);}

Note: The file cache notes the expiration time of the file
1. Get the file creation time Example:

$ctime =filectime ("Chinawinxp.txt"); echo "Creation time:". Date ("Y-m-d h:i:s", $ctime);

2. Get the file modification time example:

$mtime =filemtime ("Chinawinxp.txt"); echo "Modification time:". Date ("Y-m-d h:i:s", $mtime);

The Fileatime () function returns the last access time of the specified file

2.memcache and Redis Cache
Open service, connect port, cache server, PHP operation Redis, Mencache condition:
1) Install Phpredis extension/mencache extension
2) PHP Connection Redis service connet (127.0.0.1,6379);
Connection Mencache service connet (' Memcache_host ', 11211);
3) Set Cache
4) Get Get Cache
Set cache time: Set key time (value)

PHP cache includes both PHP compilation cache and PHP data cache. PHP is an interpreted language, which belongs to the side-compilation side of the run. The advantage of this mode of operation is that program modification is convenient, but the operation efficiency is very low. PHP compiler cache for this situation to improve processing, so that the PHP language only run once, you can put the program's compilation results cached. This way, the next run does not need to be compiled again, which greatly improves the speed of PHP operation.

Related Article

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.