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:
http://juliusbeckmann.de/code/memcache.lib.phps
Plain download:
http://juliusbeckmann.de/code/memcache.lib.txt

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:

MEMCACHE_PREFIX

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

MEMCACHE_SUFFIX

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='127.0.0.1', $port=11211)

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

if(!memcache_instance())
    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.