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.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
# 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.

1
2
3
4
5
6
7
8
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/




Related posts:

  1. Installing memcache on osx for php
  2. Custom sorting in Datatable
  3. PHP array delete an item
  4. Stop UTF 8 with javascript
  5. check file size at the client side

One thought on “Using memcache in php

Leave a Reply

Your email address will not be published.

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>