start learning
Image 1

PHP Caching Techniques

Caching is an essential technique in web development that involves storing frequently accessed data in memory to improve application performance by reducing the need to fetch data from slower data sources like databases or external APIs. Memcached and Redis are two popular in-memory data stores used for caching.


Memcached

Definition : Memcached is a distributed, high-performance, in-memory caching system. It stores data in key-value pairs and is designed to provide quick access to cached data.

// Connect to Memcached server
$memcached = new Memcached();
$memcached->addServer('localhost', 11211);

// Check if data is already cached
$cachedData = $memcached->get('my_key');

if ($cachedData === false) {
    // If data is not in cache, fetch it from the database
    $data = fetchDataFromDatabase();

    // Store the fetched data in the cache with an expiration time (e.g., 3600 seconds)
    $memcached->set('my_key', $data, 3600);
} else {
    // Data is available in cache; use it
    $data = $cachedData;
}

Redis

Definition : Redis is an open-source, advanced key-value store that supports various data structures like strings, lists, sets, and more. It is commonly used for caching, real-time analytics, and message brokering.

// Connect to Redis server
$redis = new Redis();
$redis->connect('localhost', 6379);

// Check if data is already cached
$cachedData = $redis->get('my_key');

if ($cachedData === false) {
    // If data is not in cache, fetch it from the database
    $data = fetchDataFromDatabase();

    // Store the fetched data in Redis with an expiration time (e.g., 3600 seconds)
    $redis->set('my_key', serialize($data), 3600);
} else {
    // Data is available in cache; unserialize and use it
    $data = unserialize($cachedData);
}

Clarifications :