pecl install memcache
Once installed, you need to enable the Memcache extension in your PHP configuration file (php.ini). Open the php.ini file and add the following line:
extension=memcache.so
Afterwards, restart your web server to apply the changes.
$memcache = new Memcache;
$memcache->connect('127.0.0.1', 11211);
Here, '127.0.0.1' is the IP address of your Memcache server, and 11211 is the default port number. Modify these values according to your actual server address and port.
Caching Data:
$data = 'cached data';
$key = 'cache_key';
$expiration = 3600; // Cache expiration time in seconds
$memcache->set($key, $data, 0, $expiration);
In this example, we store the string 'cached data' in a cache with the key 'cache_key', and set the expiration time to 3600 seconds (1 hour).
Retrieving Cached Data:
$key = 'cache_key';
$data = $memcache->get($key);
if ($data === false) {
// Data does not exist, regenerate and store in cache
$data = generate_data();
$memcache->set($key, $data, 0, $expiration);
}
If cached data exists, it is retrieved directly. If not, the data is regenerated and stored in the cache.
Deleting Cached Data:
$key = 'cache_key';
$memcache->delete($key);
By specifying the key, you can delete the corresponding data from the cache.
Compressing Data:
$data = 'large data';
$key = 'cache_key';
$expiration = 3600;
$memcache->set($key, gzcompress($data), MEMCACHE_COMPRESSED, $expiration);
By using the gzcompress function, you can compress the data before storing it, which reduces the network load during data transfer.
Using CAS (Check-And-Set) Operation:
$key = 'cache_key';
$cas = 0;
$data = $memcache->get($key, null, $cas);
// Modify data
$data['field'] = 'new value';
// Perform CAS operation by comparing the previously obtained $cas value
$memcache->cas($cas, $key, $data, 0, $expiration);
CAS operations help avoid issues with concurrent data modifications and ensure data consistency.