Introduction to caching techniques commonly used in PHP

Source: Internet
Author: User
Tags flock md5 memcached mixed set time

Data caching

Here is the data cache refers to the database query cache, each visit to the page, will first detect the corresponding cache data exists, if not, connect the database, get the data, and the query results serialized after saving to the file
, the same query results are obtained directly from the cached file.

The code is as follows Copy Code

<?php
$sql = ' SELECT * from users ';
$key = MD5 ($sql); Memcached Object identifier
if (!) ( $datas = $MC->get ($key))) {
When cached data is not obtained in memcached, a database query is used to get the recordset.
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;
Saves the result set data obtained in the database to memcached for use on the next visit.
$MC->add ($key, $datas);
} else {
echo "n". Str_pad (' Read datas from memcached. ', 60, ' _ '). " n ";
}
Var_dump ($datas);
?>

Page Caching

Every time you visit the page, you will first detect the corresponding cache page file exists, if it does not exist, connect the database, get the data, display the page and generate cached page files, so the next time the page file will play a role. (the template engine and some common online caching classes typically have this feature)

The code is as follows Copy Code

<?php
Define (' Directory_separator ', '/');
Define (' fopen_write_create_destructive ', ' WB ');
Define (' Fopen_write_create ', ' ab ');
Define (' Dir_write_mode ', 0777);
Class Filecache {

/**
* Cache Path
*
* @access Private
* @var String
*/
Private $_cache_path;

/**
* Cache expiration time, in seconds second
*
* @access Private
* @var int
*/
Private $_cache_expire;

/**
* Parse function, set cache expiration practices and storage path
*
* @access Public
* @return void
*/
Public function __construct ($expire, $cache _path)
{
$this->_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 a unique key to the cache
* @param string $data cached content
* @return BOOL
*/
Public function set ($key, $data)
{
$value = serialize ($data);

$file = $this->_file ($key);

return $this->write_file ($file, $value);
}

/**
* Get Cache
*
* @access Public
* @param string $key a unique key to the cache
* @return Mixed
*/
Public function Get ($key)
{
$file = $this->_file ($key);

/** file does not exist or directory is not writable/
if (!file_exists ($file) | |! $this->is_really_writable ($file))
{
return false;
}

The/** cache is 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, Delete * *
@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);//before reading plus shared locks

$data = ';
if (filesize ($file) > 0)
{
$data =& fread ($fp, FileSize ($file));
}

Flock ($FP, Lock_un);/release 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 each platform to determine whether the 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" installations 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;
}
}
$cache = new Filecache (' 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 caching system for reducing database load and increasing access speed in dynamic applications.
Dbcached is a distributed Key-value database memory caching system based on Memcached and Nmdb.

Although the above caching technology is very good to solve the problem of frequent query database, but its disadvantage is that the data is not time-sensitive, below I give my common methods in the project:

The code is as follows Copy Code

? Php

Class Memcachemodel {
Private $MC = null;
/**
* Constructs a method for adding servers and creating memcahced objects
*/
function __construct () {
$params = Func_get_args ();
$MC = new Memcache;
If you have multiple memcache servers
if (count ($params) > 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 Memcached Object
* @return Object Memcached objects
*/
function Getmem () {
return $this->mc;
}
/**
* Check if MEM is connected successfully
* @return BOOL Connection successfully returns TRUE, otherwise returns false
*/
function Mem_connect_error () {
$stats = $this->mc->getstats ();
if (empty ($stats)) {
return false;
}else{
return true;
}
}
Private Function Addkey ($tabName, $key) {
$keys = $this->mc->get ($tabName);
if (empty ($keys)) {
$keys =array ();
}
If key does not exist, add a
if (!in_array ($key, $keys)) {
$keys []= $key; Add a new key to the keys in this table
$this->mc->set ($tabName, $keys, memcache_compressed, 0);
return true; Does not exist returns true
}else{
return false; Existence returns false
}
}
/**
* Add data to the Memcache
* @param string $tabName table name to cache the datasheet
* @param string $sql Use SQL as key for Memcache
* @param mixed $data data that needs to be cached
*/
function Addcache ($tabName, $sql, $data) {
$key =md5 ($sql);
If there is no
if ($this->addkey ($tabName, $key)) {
$this->mc->set ($key, $data, memcache_compressed, 0);
}
}
/**
* Get the data saved in the MEMCAHCE
* @param string $sql key with SQL
* @return Mixed returns the data in the cache
*/
function GetCache ($sql) {
$key =md5 ($sql);
return $this->mc->get ($key);
}

/**
* Delete all caches related to the same table
* @param string $tabName table name for data table
*/
function Delcache ($tabName) {
$keys = $this->mc->get ($tabName);
Delete all caches of the same table
if (!empty ($keys)) {
foreach ($keys as $key) {
$this->mc->delete ($key, 0); 0 means delete immediately
}
}
Delete all SQL key for a table
$this->mc->delete ($tabName, 0);
}
/**
* Delete the cache of a single statement
* @param the SQL statement executed by string $sql
*/
function DeLone ($sql) {
$key =md5 ($sql);
$this->mc->delete ($key, 0); 0 means delete immediately
}
}

Time Trigger Cache

Check that the file exists and that the timestamp is less than the set expiration time, or update the cache if the timestamp of the file modification is greater than the current timestamp minus the expiration time.
Set time not to determine whether the data to update, over the set time to update the cache. The above is only suitable for the timeliness of the use of the situation is not high, otherwise please see below.

Content Trigger Cache

Forces an update of the cache when data is inserted or updated.

Here we can see that when a large amount of data needs to be updated frequently, it involves disk read and write operations. How to solve it? I usually do not cache everything in my daily projects, but I cache something that is not always changed. However, in the case of heavy load, it is best to use shared memory to do the caching system.

Here the PHP cache may be a bit of a solution, but the downside is that because each request still has to be parsed by PHP, the efficiency problem is even worse in the case of a heavy load, in which case a static cache may be used.

Static caching

Static caching here refers to HTML caching, where HTML caching is generally not necessary to determine whether data is to be updated, as usually in the case of HTML, where the content is infrequently changed. When the data is updated, you can also force the HTML to be updated.

There are also static caches like the thinkphp

Thinkphp Official Handbook writes that there are three ways to define static rules:

The code is as follows Copy Code

Return Array (

' ActionName ' =>array (' Static rules ', ' static cache validity ', ' additional rules '),//First

' Modulename:actionname ' =>array (' Static rules ', ' static cache validity ', ' additional rules '),//second

' * ' =>array (' Static rules ', ' static cache validity ', ' additional rules '),//Third

... Static rules for more operations

)

The first is to define the global operational static rules, such as the static rules that define all the read operations: ' read ' =>array (' {id} ', ' 60 ')
where {ID} means to take $_get[' ID ' as a static cache filename, and the second parameter represents 60 seconds of caching.

The second is a static rule that defines the operation of a module, for example, we need to define the read operation of the blog module for static caching

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

The third way is to define a global static caching rule, which is used in special cases where any module's operation is applicable, for example

' * ' =>array (' {$_server. REQUEST_URI|MD5} '), cached according to the current URL.

Here I write in the static cache rule file htmls.php:

PHP code

The code is as follows Copy Code
<?php return Array (' gethtml ' => Array (' {: action} ',-1),//-1 indicates permanent cache); ?>

Smarty Cache:

  code is as follows copy code

<?php
require ('./smarty/smarty.class.php ');
$smarty = new Smarty;

$smarty->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 ')
?

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.