Install the Memcache extension:
pecl install memcache
Edit your php.ini file to include the extension:
extension=memcache.so
Restart your web server:
service apache2 restart
Connect to the Memcache server:
$memcache = new Memcache;
$memcache->connect('localhost', 11211) or die("Unable to connect to Memcache server");
Store data in the cache:
$key = "user_id_123";
$data = array("name" => "John", "age" => 25);
$expiration = 60; // Cache duration in seconds
$memcache->set($key, $data, false, $expiration);
Retrieve data from the cache:
$key = "user_id_123";
$data = $memcache->get($key);
if ($data === false) {
// Data not found or expired
} else {
// Data exists
echo $data["name"]; // Outputs John
echo $data["age"]; // Outputs 25
}
Increment and decrement values:
$key = "counter";
$memcache->add($key, 0); // Initialize to 0
$memcache->increment($key); // Increment by 1
$memcache->increment($key, 5); // Increment by 5
$memcache->decrement($key); // Decrement by 1
$memcache->decrement($key, 3); // Decrement by 3
Delete cached data:
$key = "user_id_123";
$memcache->delete($key);
Use unique keys for storage:
$key = "user_id_123";
$data = array("name" => "John", "age" => 25);
$memcache->set($key, $data);
// Retrieve data
$data = $memcache->get($key);
Namespace usage example:
$namespace = "user_123";
$key = "name";
$data = "John";
$memcache->set("$namespace:$key", $data);
// Retrieve namespaced data
$data = $memcache->get("$namespace:$key");