How to check for empty result set vs. unset key in Memcached in CakePHP
I'm using Mem开发者_JS百科cached in a CakePHP application to cache MySQL result sets. One result set that I'm caching is empty about half the time.
The problem I'm having is that when the result set is empty and I set the Memcached key, it sets the empty/false result from CakePHP's find method.
When I check the Memcached key in my script on the next page load, it runs the query again because reading the Memcached key's value must return false.
Here's my general Memcached logic using the CakePHP Cache utility:
if(!$resultsArray = Cache::read('results_array')) {
$resultsArray = $this->Model->find('all', $params);
Cache::write('results_array', $resultsArray);
}
What's the best practice to check the cache to distinguish between a Memcached key that doesn't exist and a key that contains a false/empty value from a previous find function? (maybe this is more about PHP/programming than Memcached).
Suggestion:
if (($resultsArray = Cache::read('results_array')) === false) {
$resultsArray = $this->Model->find('all', $params);
if (!$resultsArray) {
$resultsArray = null;
}
Cache::write('results_array', $resultsArray);
}
I don't have enough experience with Memcached though to be able to tell you if the false
/null
distinction will work correctly, but it should theoretically.
You should use the strict comparison operator (!==
or ===
) to distinguish false
from an empty value.
But I don't think there's a way to distinguish between a cached value of false
from a Memcached key that doesn't exist.
精彩评论