PHP Development App Interface Learning notes and summary-app interface example [3] Home App interface Development ② Read cache mode

Source: Internet
Author: User
Tags sprintf delete cache

Take the static cache as an example.

Modify file.php line:11 Remove the Path parameter (convenient), plus the cache time parameter:

 Public function cachedata ($k,$v = ",$cacheTime = 0) {     // filename       $filename$this->_dir.$k. Self::EXT;       .....

The line:25 sets the cache time to 11 digits, and if it is less than 11 bits, it is 0 before the time. And then splicing the cache time and cache content:

$cacheTime sprintf ('%011d ',$cacheTime);    // $cacheTime set to 11-bit (convenient interception), less than 11 front complement 0//the cache time stitching $v return file_put_contents ($filename,$cacheTime. Json_encode ($v));

Test it:

$file New Cache (); $file->cachedata (' Data ', ' Index-data ', 50);

Open Data.txt:

00000000050 "Index-data"

Then modify the Read cache line33:

$contents=file_get_contents($filename);$cacheTime= (int)substr($contents, 0,11);$val=substr($contents, 11);if($cacheTime! = 0 &&$cacheTime+Filemtime($filename) < Time()){//Cache has expired    unlink($filename); return false;}returnJson_decode ($val,true);

Introduction of file.php in list.php

Modify Line:14

$cache=NewCache ();$vals=Array();if(!$vals=$cache->cachedata (' Index-data ').$page.‘ -‘.$pageSize)){    //echo ' aaaa '; exit ();//test cache invalidation    Try{        $connect= Db::getinstance ()Connect (); }Catch(Exception $e){        returnResponse::show (403, ' Database connection failed '); }    $res=mysql_query($sql,$connect);  while($val=Mysql_fetch_assoc($res)){        $vals[] =$val;//two-dimensional arrays    }    if($vals){        $cache->cachedata (' Index-data ').$page.‘ -‘.$pageSize,$vals, 50); }

Test page:

Http://127.0.0.17/php/APP/list.php?pageSize=10&page=3

When the cache fails (no comment echo ' aaaa '; exit (); ), page output: AAA

list.php

<?PHPrequire_once' Response.php ';require_once' Db.php ';require_once' File.php ';$page=isset($_get[' page '])?$_get[' Page ']:1;$pageSize=isset($_get[' PageSize '])?$_get[' PageSize ']:1;if(!Is_numeric($page) || !Is_numeric($pageSize)){    return@Response:: Show (401, ' data not valid '));}$offset= ($page-1) *$pageSize;//number of start per page$sql= ' SELECT * from review where is_enabled = 1 order BY creation_time desc limit '.$offset.‘,‘.$pageSize;$cache=NewCache ();$vals=Array();//When there is no cache or cache is invalidated, connect to the database and fetch data from the database//Note that paging information needs to be written to the file name when there is paging dataif(!$vals=$cache->cachedata (' Index-data ').$page.‘ -‘.$pageSize)){    //echo ' aaaa '; exit ();//test cache invalidation    Try{        $connect= Db::getinstance ()Connect (); }Catch(Exception $e){        returnResponse::show (403, ' Database connection failed '); }    $res=mysql_query($sql,$connect);  while($val=Mysql_fetch_assoc($res)){        $vals[] =$val;//two-dimensional arrays    }    //at the same time, the extracted data is cached    if($vals){        $cache->cachedata (' Index-data ').$page.‘ -‘.$pageSize,$vals, 50); }}//if the cache exists and is not invalidated, encapsulate the data in the cache using the encapsulated interface classif($vals){    returnResponse::show (200, ' Home data acquisition success ',$vals);}Else{    returnResponse::show (400, ' Home data acquisition failed ',$vals);}

Test http://127.0.0.17/php/APP/list.php?pageSize=10&page=3 Build Index-data3-10.txt

Test http://127.0.0.17/php/APP/list.php?pageSize=10 Build Index-data1-10.txt

Attached: file.php:

1<?PHP2 classcache{3     //static cache file suffix name4     ConstEXT = ' txt ';5     //defining cache file Storage Paths6     Private $_dir;7      Public function__construct () {8         $this->_dir =dirname(__file__).‘ /files/';9     }Ten  One      Public functionCacheData ($k,$v= ",$cacheTime= 0) {//default permanent not invalidated A //File name -         $filename=$this->_dir.$k.‘.‘. Self::EXT; -         //$v not for ': Store cache or delete cache the         if($v!== "){ -             //Delete Cache -             if(Is_null($v)){ -                 return@unlink($filename); +             } -             //Storage Cache +             $dir=dirname($filename); A             if(!Is_dir($dir)){ at                 mkdir($dir, 0777); -             } -             $cacheTime=sprintf('%011d ',$cacheTime);//$cacheTime set to 11 bits (for easy interception), less than 11 bits in front of 0 - //The cache time stitching $v -             return file_put_contents($filename,$cacheTime. Json_encode ($v)); -         } in         //Read Cache -         if(!Is_file($filename)){ to             return false; +         } -         $contents=file_get_contents($filename); the         $cacheTime= (int)substr($contents, 0,11); *         $val=substr($contents, 11); $         if($cacheTime! = 0 &&$cacheTime+Filemtime($filename) < Time()){//Cache has expiredPanax Notoginseng             unlink($filename); -             return false; the         } +         returnJson_decode ($val,true); A     } the}
View Code

Reference:

Study notes on the sprintf () function in PHP

PHP Development App Interface Learning notes and summary-app interface example [3] Home App interface Development ② Read cache mode

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.