Memcache is a distributed object caching system and uses key-value
for storing small data. Before you start calling Memcache
code into PHP, you need to make sure that it is installed. That can be done using class_exists
method in php. Once it is validated that the module is installed, you start with connecting to memcache server instance.
if (class_exists('Memcache')) {
$cache = new Memcache();
$cache->connect('localhost',11211);
}else {
print "Not connected to cache server";
}
This will validate that Memcache php-drivers are installed and connect to memcache server instance running on localhost.
Memcache runs as a daemon and is called memcached
In the example above we only connected to a single instance, but you can also connect to multiple servers using
if (class_exists('Memcache')) {
$cache = new Memcache();
$cache->addServer('192.168.0.100',11211);
$cache->addServer('192.168.0.101',11211);
}
Note that in this case unlike connect , there wont be any active connection until you try to store or fetch a value.
In caching there are three important operations that needs to be implemented
$cache
or memcached class object has a set
method that takes in a key,value and time to save the value for (ttl).
$cache->set($key, $value, 0, $ttl);
Here $ttl or time to live is time in seconds that you want memcache to store the pair on server.
$cache
or memcached class object has a get
method that takes in a key and returns the corresponding value.
$value = $cache->get($key);
In case there is no value set for the key it will return null