Introduction to common cache technologies in PHP

Source: Internet
Author: User
Tags flock
Data cache: the data cache here refers to the database query cache. each time you access the page, it first checks whether the cache data exists. if it does not exist, it connects to the database to obtain the data, serialize the query results and save them to the file. then, the same query results will go straight... data cache: the data cache here refers to the database query cache. each time you access the page, it first checks whether the cache data exists. if it does not exist, it connects to the database to obtain the data, serialize the query result and save it to the file. the same query result will be obtained directly from the cache file. the code is as follows:

 Get ($ key) {// if no cached data is obtained in memcached, use database query to obtain the record set. Echo "\ n ". str_pad ('read datas from MySQL. ', 60 ,'_'). "\ n"; $ conn = mysql_connect ('localhost', 'test', 'test'); mysql_select_db ('test'); $ result = mysql_query ($ SQL ); while ($ row = mysql_fetch_object ($ result) $ datas [] = $ row; // Save the result set data obtained from the database to memcached, for the next access. $ Mc-> add ($ key, $ datas);} else {echo "\ n ". str_pad ('read datas from memcached. ', 60 ,'_'). "\ n" ;}var_dump ($ datas) ;?>

Page cache: each time you access a page, the system first checks whether the corresponding cached page file exists. if it does not exist, it connects to the database to obtain data, displays the page, and generates cache page files at the same time, in this way, the page file will play a role in the next visit. the template engine and some common cache classes on the Internet usually have this function. the code is as follows:

 _ Cache_expire = $ expire; $ this-> _ cache_path = $ cache_path ;} /*** cache file name ** @ access public * @ param string $ key * @ return void */private function _ file ($ key) {return $ this-> _ cache_path. md5 ($ key );} /*** set cache ** @ access public * @ param string $ key the unique key of the cache * @ param string $ data cached content * @ return bool */public function set ($ key, $ data) {$ value = serialize ($ data); $ file = $ this-> _ file ($ key); retu Rn $ this-> write_file ($ file, $ value );} /*** get cache ** @ access public * @ param string $ key the unique key of the cache * @ return mixed */public function get ($ key) {$ file = $ this-> _ file ($ key);/** the file does not exist or the directory cannot be written */if (! File_exists ($ file) |! $ This-> is_really_writable ($ file) {return false;}/** the cache has not expired and is still available */if (time () <(filemtime ($ file) + $ this-> _ cache_expire) {$ data = $ this-> read_file ($ file); if (FALSE! ==$ Data) {return unserialize ($ data);} return FALSE;}/** Cache expired, deleted */@ unlink ($ file); return FALSE ;} function read_file ($ file) {if (! File_exists ($ file) {return FALSE;} if (function_exists ('File _ get_contents ') {return file_get_contents ($ file);} if (! $ Fp = @ fopen ($ file, FOPEN_READ) {return FALSE;} flock ($ fp, LOCK_SH); // add a shared lock before reading $ data = ''; if (filesize ($ file)> 0) {$ data = & fread ($ fp, filesize ($ file);} flock ($ fp, LOCK_UN ); // release the lock fclose ($ fp); return $ data;} function write_file ($ path, $ data, $ mode = FOPEN_WRITE_CREATE_DESTRUCTIVE) {if (! $ Fp = @ fopen ($ path, $ mode) {return FALSE;} flock ($ fp, LOCK_EX); fwrite ($ fp, $ data); flock ($ fp, LOCK_UN); fclose ($ fp); return TRUE;} function is_really_writable ($ file) // compatible with various platforms to determine whether a file has write permission {// If we're on a Unix server with safe_mode off we call is_writable if (DIRECTORY_SEPARATOR = '/' AND @ ini_get ("safe_mode ") = FALSE) {return is_writable ($ file);} // For windows servers and safe_mode "on" I Nstallations we'll actually // write a file then read it. bah... if (is_dir ($ file) {$ file = rtrim ($ file ,'/'). '/'. md5 (rand (1,100); if ($ fp = @ fopen ($ file, FOPEN_WRITE_CREATE) ==== FALSE) {return FALSE;} fclose ($ fp ); @ chmod ($ file, DIR_WRITE_MODE); @ unlink ($ file); return TRUE;} elseif ($ fp = @ fopen ($ file, FOPEN_WRITE_CREATE) === FALSE) {return FALSE;} fclose ($ fp); return TRUE ;}}$ cac He = new FileCache (30, 'cache/'); $ cache-> set ('test', 'This is a test. '); print $ cache-> get ('test');/* End of file FlieCache. php */?>

Memory cache: Memcached is a high-performance, distributed memory object cache system that reduces database loads in Dynamic Applications and improves access speeds.

Dbcached is a distributed key-value database memory cache system based on Memcached and NMDB.

Although the above caching technology can solve the problem of frequent database queries, its disadvantage is that the data is not time-sensitive. below I will provide a common method for my project, the code is as follows:

 1) {foreach ($ params as $ v) {call_user_func_array (array ($ mc, 'addserver'), $ v );} // if there is only one memcache server} else {call_user_func_array (array ($ mc, 'addserver'), $ params [0]) ;}$ this-> mc = $ mc ;} /*** get the memcached object * @ return object memcached object */function getMem () {return $ this-> mc ;} /*** check whether mem connection is successful * @ return true if bool connection is successful, otherwise false */function mem_connect_error () {$ stats = $ this-> mc-> ge TStats (); if (emptyempty ($ stats) {return false;} else {return true ;}} private function addKey ($ tabName, $ key) {$ keys = $ this-> mc-> get ($ tabName); if (emptyempty ($ keys) {$ keys = array ();} // if the key does not exist, add an if (! In_array ($ key, $ keys) {$ keys [] = $ key; // add the new key to the keys of the table $ this-> mc-> set ($ tabName, $ keys, MEMCACHE_COMPRESSED, 0); return true; // returns true if no result exists} else {return false; // Return false}/*** add data to memcache * @ param string $ tabName: name of the table in which the data table needs to be cached * @ param string $ SQL uses SQL as the key of memcache * @ param mixed $ data the data to be cached */function addCache ($ tabName, $ SQL, $ data) {$ key = md5 ($ SQL); // if there is no if ($ this-> addKey ($ t AbName, $ key) {$ this-> mc-> set ($ key, $ data, MEMCACHE_COMPRESSED, 0 );}} /*** get the data stored in memcahce * @ param string $ SQL use the SQL key * @ return mixed to return the cached data */function getCache ($ SQL) {$ key = md5 ($ SQL); return $ this-> mc-> get ($ key );} /*** delete all the caches related to the same table * @ param string $ tabName table name */function delCache ($ tabName) {$ keys = $ this-> mc-> get ($ tabName); // delete all the caches of the same table if (! Emptyempty ($ keys) {foreach ($ keys as $ key) {$ this-> mc-> delete ($ key, 0 ); // 0 indicates immediate deletion} // key $ this-> mc-> delete ($ tabName, 0) of all SQL statements in the table );} /*** delete the cache of a separate statement * @ param string $ SQL statement */function delone ($ SQL) {$ key = md5 ($ SQL ); $ this-> mc-> delete ($ key, 0); // 0 indicates immediate deletion}?>

Time-triggered cache: Check whether the file exists and the timestamp is earlier than the set expiration time. if the modified timestamp of the file is greater than the current timestamp minus the expiration timestamp, the file is cached, otherwise, the cache is updated.

If you do not judge whether the data is to be updated within the specified time period and then update the cache after the specified time, the above is only applicable when the requirements for timeliness are not high. otherwise, please refer to the following.

Content-triggered cache: when data is inserted or updated, the cache is forcibly updated.

Here we can see that when a large amount of data frequently needs to be updated, disk read/write operations will be involved in the end. how can this problem be solved? In my daily projects, I usually do not cache all the content, but cache a part of the content that is not changed frequently. but in the case of heavy load, it is best to use shared memory as a cache system.

Here, PHP Cache may be a solution, but its disadvantage is that, because every request still needs to be parsed by PHP, the efficiency problem is still serious under heavy load conditions, in this case, static cache may be used.

Static cache: the static cache here refers to the HTML cache. The HTML cache generally does not need to judge whether the data is to be updated, because HTML is usually used for pages that do not change content frequently, you can forcibly update HTML during data update.

There is also a static cache like thinkphp. the ThinkPHP official manual writes that there are three methods to define static rules. The code is as follows:

 Array ('static rules', 'static cache validity period ', 'additional rules'), // The first type of 'modulename: actionname' => array ('static rule ', 'static cache validity set', 'additional rule'), // type 2 '*' => array ('static rule', 'static cache validity set', 'additional rule '), // The third... More static operation rules)?>

The first is to define global static operation rules. for example, to define static rules for all read operations: 'read' => array ('{id}', '60 ').

{Id} indicates that $ _ GET ['id'] is the static cache file name, and the second parameter indicates that the cache is 60 seconds.

The second is to define the static rules for operations of a module. for example, we need to define the read operation of the Blog module for static cache.

'Blog: read' => array ('{id}',-1 ).

The third method is to define global static cache rules. this is a special case, and any module operation applies. for example:

'*' => Array ('{$ _ SERVER. REQUEST_URI | md5}'), which is cached based on the current URL.

I am writing it in the static cache rule file htmls. php. the code is as follows:

 Array ('{: action}',-1), //-1 indicates permanent cache);?>

The SMARTY cache code is as follows:

 caching = true;    if (!$smarty->is_cached('index.tpl')) {        // No cache available, do variable assignments here.        $contents = get_database_contents();        $smarty->assign($contents);    }    $smarty->display('index.tpl');?>


Address:

Reprinted at will, but please attach the article address :-)

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.