PHP: Easy Memcache handling

In a current project of mine i needed the use of a universal caching system.
After testing a little bit with APC i found memcache that will do the job perfectly.
So i wrote a few tiny functions for easy memcache handling.

The code can be found here:
With highlighting:
Plain download:

I wrote the code with the idea in mind that i could simply use this 3 cache_* functions without having to handle a memcache object. Till now this code works flawlessly on my project.

I added PHPDoc Comments but want to give some advices here:

You can use 2 constants for the functions if you want to run multiple systems with one memcache cache:


This will add a prefix to every $key. This is done inside the functions, no need to interact from outside.


This will add a suffix to every $key.
If you do not use this constants, you can safely remove the 4 lines in every cache_* function.

function & memcache_instance($ip='', $port=11211)

This functions returns a reference to the current memcache connection.
If you want to check if memcache connection is available:

    echo "Memcache not available!";

function cache_set($key, $val, $ttl=0, $compress=false)

This is the set function. The name is selected universally so you can exchange the code easy. It will return FALSE if $key could not be set.
$ttl = 0 means caching forever, or it gets purged.
$compress = true would let memcache compress the $val with zlib. This only makes sense on huge arrays or objects.

function cache_get($key)

Simple get function returns FALSE or the $val of $key.

function cache_del($key, $timeout=0)

This is the delete function. It will return TRUE if the delete command was successful.
$timout = 0 means deleting immediately. A value of 60 would delete the $key in 60 seconds.

No related posts.


Die Kommentarfunktion zu diesem Beitrag wurde deaktiviert.