# PHP Memcached PHP Sessions don't work on clusters, memcached provides a solution. The procedure is as follows: ``` create a new Memcached object call memcached::addServer retrieve the value with memcached::get if the value was retrieved successfully carry on else store the value with memcached::set ``` * When the page is first loaded, the value will not be found in the cache (obviously), so we need to store it. * When the page is loaded subsequently the value should be found, the program can proceed normally. * There is a timeout, after which time the value will be removed. Many memcached members have a default parameter to set your own timeout. This is a hint only. From Wikipedia: >"Memcached's APIs provide a very large hash table distributed across multiple machines. When the table is full, >subsequent inserts cause older data to be purged in least recently used (LRU) order. Applications using >Memcached typically layer requests and additions into RAM before falling back on a slower backing store, such >as a database". ## A little experiment The first time round the value is not found, so we store it. Subsequently it is retrieved successfully. We can reset by adding ?reset=1 to the uri. ``` // reset if (isset($_GET['reset'])) { echo "Deleting cached value"; $cache->delete('testValue'); echo "Result is " . $cache->getResultMessage(); exit(); } // Try to retrieve the cached value $cachedValue = $cache->get('testValue'); if ($cachedValue) { // we got the value echo "Value successfully retrieved: $cachedValue "; } else { // value not found, so store it echo "failed to retreive testvalue, so setting testvalue"; $cache->set('testValue', 12345); } echo "Result was " . $cache->getResultMessage(); ``` ## Profiler results ``` constructor 0.5 addServer 0.5 set 21.5 get 57.7 ```