memcache is not storing data accross requests
Posted
by morpheous
on Stack Overflow
See other posts from Stack Overflow
or by morpheous
Published on 2010-04-19T23:45:05Z
Indexed on
2010/04/19
23:53 UTC
Read the original article
Hit count: 290
I am new to using memcache, so I may be doing something wrong.
I have written a wrapper class around memcache. The wrapper class has only static methods, so is a quasi singleton.
The class looks something like this:
class myCache
{
private static $memcache = null;
private static $initialized = false;
public static function init()
{
if (self::$initialized)
return;
self::$memcache = new Memcache();
if (self::configure()) //connects to daemon
{
self::store('foo', 'bar');
}
else
throw ConnectionError('I barfed');
}
public static function store($key, $data, $flag=MEMCACHE_COMPRESSED, $timeout=86400)
{
if (self::$memcache->get($key)!== false)
return self::$memcache->replace($key, $data, $flag, $timeout);
return self::$memcache->set($key, $data, $flag, $timeout);
}
public static function fetch($key)
{
return self::$memcache->get($key);
}
}
//in my index.php file, I use the class like this
require_once('myCache.php');
myCache::init();
echo 'Stored value is: '. myCache::fetch('foo');
The problem is that the myCache::init() method is being executed in full everytime a page is requested. I then remembered that static variables do not maintain state accross page requests. So I decided instead, to store the flag that indicates whether the server contains the start up data (for our purposes, the variable 'foo', with value 'bar') in memcache itself.
Once the status flag is stored in memcache itself, It solves the problem of the initialisation data being loaded for every page request (which quite frankly, defeats the purpose of memcache). However, having solved that problem, when I come to fetch the data in memcache, it is empty. I dont understand whats going on.
Can anyone clarify how I can store my data once and retrieve it accross page requests?
BTW, (just to clarify), the get/set is working correctly, and if I allow memcache to load the initialisation data for each page request, (which is silly), then the data is available in memcache.
© Stack Overflow or respective owner