How do I check in PHP if a value is stored in Memcache without fetching it? I don\'t like fetching it because the values I have set are all 1MB in size and after I fetch it, I h
I needed a reliable test to know wether to use memcache Set or memcache replace.
This is what I ended up with.
Another option would be to set up a network socket to the memcache query, but in the end it would end up doing the same and this connection already exists, saving me the overhead of making and maintaining another connection like in Joel Chen's answer.
$key = 'test';
$value = 'foobarbaz';
/**
* Intricate dance to test if key exists.
* If it doesn't exist flags will remain a boolean and we need to use the method set.
* If it does exist it'll be set to integer indicating the compression and what not, then we need to use replace.
*/
$storageFlag = (is_null($value) || is_bool($value) || is_int($value) || is_float($value) ? false : MEMCACHE_COMPRESSED);
$flags = false;
$memcache->get($key, $flags);
if(false === $flags) {
$memcache->set($key, $value, storageFlag , $minutes);
}
else {
$memcache->replace($key, $value, storageFlag, $minutes);
}
Now if you have "large data" the solution is fairly simple. Use a second key in cojoin that contains something simple like an integer to check. Always use them together and you have no issues.
$key = 'test';
$value = 'foobarbaz';
$storageFlag = (is_null($value) || is_bool($value) || is_int($value) || is_float($value) ? false : MEMCACHE_COMPRESSED);
$flags = false;
$exist_key = $key.'_exists';
$memcache->get($exist_key, $flags);
if(false === $flags) {
$memcache->set($key, $value, storageFlag , $minutes);
$memcache->set($exist_key, 42, false , $minutes);
}
else {
$memcache->replace($key, $value, storageFlag, $minutes);
$memcache->replace($exist_key, 42, false , $minutes);
}