Saturday, 24 December 2011

what is memcache?why memcache?


Memcache is basically is a generalpurpose distributed memory caching system, put that in English, it allows you to store any form of data in a ‘temporary cache’ so wherever you go to do a database query, instead of just connecting to the database and getting the data we want we first check the memcache to see if our data is already stored. If the memcache returns nothing, then go to the database, get what you’re looking for, then store it in the memcache for later:
There are five main functions that we use with Memcache and they are as follows:
  • get() – gets the value for a specified key
  • set() – sets a given key with a given value
  • add() – adds to the cache, only if it doesn’t already exist
  • replace() – sets in the cache only if the key already exists
  • flush() – removes all keys and cached data
mem1

The Code

So once you have Memcache installed on your server you can connect to it and start caching stuff. It’s worth pointing out that you shouldn’t go out and cache everything, it’s really only useful when you have large amounts of data that are going to be requested regularly.
  1. So the first two lines setup the connection to Memcache.
  2. The include is just my database connection script.
  3. Next we set the key. When we store data using Memcache there are 3 parts to storing the data, those three parts are the key, the value, and the expiry time of the cached item. The key is used to reference the stored data. in this example you can see that the key is an MD5 hash of the database query.
  4. we then check if the key exists in the cache. this will return true or false. if the data is found in the cache then we can access it.
  5. If the data isn’t found in the cache we connect to the database to get it. we store the data in the cache by using the follow line: $memcache->set($key, $row, TRUE, 20); $row refers to the array that we get from the database, notice the 20 at the end. This refers to the how long this item will expire in the cache. It is measured in seconds.
01$memcache new Memcache;
02$memcache>connect('127.0.0.1', 11211) or die ("Could not connect");
03 
04include('includes/connect.php');
05 
06//set the key then check the cache
07$key = md5("SELECT * FROM memcached_test where name='ashley'");
08$get_result $memcache>get($key);
09if ($get_result) {
10echo $get_result['name'];
11echo $get_result['username'];
12echo "Data Pulled From Cache";
13}
14else {
15 // Run the query and get the data from the database then cache it
16 $query="SELECT * FROM memcached_test where name='ashley';";
17 $result = mysql_query($query);
18 $row = mysql_fetch_array($result);
19 print_r($row);
20 $memcache>set($key$row, TRUE, 20); // Store the result of the query for 20 seconds
21 echo "Data Pulled from the Database";
22}
This is a very simple example of how to use memcache, but I hope it has been an insight into how caching works.
Some classes available for memcache
This class can store and retrieve data in a Memcache server.

It can connect to a given Memcache server and perform several types of operations with cached data entries using the PHP Memcache class.

The class can check of an cache entry with a given name exists, store a value in an entry, retrieve the value of an entry, and delete an entry.


The class can automatically add a prefix to the name of the cached entries. 


here is the Class.
<?php
Class Cache {

    private 
$prefix$cur_key$cur_cache;

    public static function 
getInstance()
    {
        static 
$instance null;
        if(
$instance == null)
        
$instance = new Cache();
        return 
$instance;
    }
    
    public function 
__construct()
    {
        if(!
function_exists('memcache_connect'))
        {
            die(
'Memcache is not currently installed...');
        } else {
        
            
$this->memcache = New Memcache;
            if(!
$this->memcache->connect("localhost""11211"))
            {
                die(
'Could not connect to the Memcache host');
            }
            
$this->prefix "aiw_";
        
        }
    }
    
    public function 
exists($key)
    {
        if(
$this->memcache->get($this->prefix $key))
        {
            
$this->cur_cache $this->memcache->get($this->prefix $key);
            
$this->cur_key $this->prefix $key;
            return 
true;
       } else 
       {     
            return 
false
       }
       
      }
    
    public function 
delete($key)
    {
        if(
$this->memcache->get($this->prefix $key))
        {
            return 
$this->memcache->delete($this->prefix $key);
            
        } else
        {
            return 
false;
        }
    }
    
    public function 
flush()
    {
        
$this->memcache->flush();
    }
    
    public function 
update($key$data$interval)
    {
        
$interval = (isset($interval)) ? $interval 60 60 0.15;
        
        if(
$this->prefix $this->cur_key)
        {
            if(!empty(
$this->cur_cache))
            {
            return    
$this->memcache->replace($this->cur_key$dataMEMCACHE_COMPRESSED$interval);
            }
        } elseif (
$this->memcache->get($this->prefix $key))
        {
            return 
$this->memcache->replace($this->prefix $key$dataMEMCACHE_COMPRESSED$interval);
        } else
        {
            return 
false;
        }
    }
    
    public function 
get($key)
    {
        if((
$this->prefix $key) == $this->cur_key)
        {
            return 
$this->cur_cache;
        } else {
            return 
$this->memcache->get($this->prefix $key);
        }
    }
    
    public function 
set($key$data$interval)
    {   
        
$interval = (isset($interval)) ? $interval 900;
        return 
$this->memcache->set($this->prefix $key$dataMEMCACHE_COMPRESSED$interval);
    }
    
}
     
?>



How to use this class:


<?php 


include('./memcache.class.php'); 


$cache = Cache::getInstance(); 


//Checking if the the key exists 
if($cache->exists("key")) 

    echo $cache->get("key"); 
} else { 
    $cache->set("key", "It's cached!", "900"); 

//Setting data in the memory 
if(!cache->exists("hello")) 

   $cache->set("hello", "Hello! this is my cached data for 6 hours!", 60 * 60 * 6); //Interval: 60 * 60 * 6 (6 hours) or 21600 in seconds
   echo $cache->get("hello"); 



//Replacing data for its key 
if($cache->exists("test")) 

    $cache->update("key", "Here is my newly replaced data for the key (key) for one hour!", 60 * 60 * 1); 



//Deleting data for a key 
if($cache->exists("key")) 

   $cache->delete("key"); //We've now deleted the data for the key (key)! 



//Flushing a projects memory block 
$cache->flush(); //All the data for our prefix is now gone! 


?>





No comments:

Post a Comment