Jun27

Using memcache in php

Posted by: Brian Chan | Filed in: technology | Tags: , | 06:47 pm, June 27th, 2012 Add comments

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 Response to “Using memcache in php”

  1. Installing memcache on osx for php Says:

    [...] php is ready to interact with memcache. But just how to do that in code? Let’s wait for my part 2 of this [...]

Leave a Reply