Using memcache in php

So now I assumed you already got memcache running. If not, check out my previous tutorial on how to do that.

Now in your php project, include the following code somewhere in your init.php file. Or you can always make it object oriented if you like.

# Connect to memcache:
global $memcache;
global $memcache_server_up;
$memcache = new Memcache;
$memcache_server_up = $memcache->connect('127.0.0.1', 11211);

# check to see if memcache server is up
function memcache_server_is_up(){
	global $memcache_server_up;
	return $memcache_server_up;
}

# Gets key / value pair into memcache
function getCache($key) {
	global $memcache;
	if (memcache_server_is_up()) {
		return $memcache->get($key);
	}else{
		return "";
	}
}

# Puts key / value pair into memcache
function setCache($key, &$object, $timeout = 600) {
	global $memcache;
	if (memcache_server_is_up()) {
		return $memcache->set($key,$object,MEMCACHE_COMPRESSED,$timeout);
	}
}

My setup will work if you have only one memcache daemon running. If you have a few, then make your changes accordingly.

So in your actual code, just do something like the following.

include_once "init.php";

$cache_key = "a key that uniquely identifies your object";
$obj = getCache($cache_key);
if ($obj == ""){
	$obj = generate_your_obj_somehow();
	setCache($cache_key, $obj, 60*60);
}

So, the idea is to use our cache if it exists. If not, generate our object and then store it in memcache. The above 60*60 will store the $obj for an hour.

Simple idea, but great performance! You can also set up background scripts to keep refreshing your frequently-used objects, so that there is no load time penalty for your users.

Bonus: install this script to see your memcache status! http://livebookmark.net/journal/2008/05/21/memcachephp-stats-like-apcphp/

ref: http://pureform.wordpress.com/2008/05/21/using-memcache-with-mysql-and-php/

One thought on “Using memcache in php

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s