Implementing a Redis Cache for Product Catalog Data in PHP

Implementing a Redis Cache for Product Catalog Data in PHP

On8th Nov 2024, 2024-12-04T09:52:41+05:30 ByKarthik Kumar D K | read
Listen Pause Resume Stop

Caching is a vital technique for improving application performance, especially in e-commerce platforms where product catalog data is frequently accessed. By using Redis as a caching layer, you can significantly reduce database load and improve response times for users.

In this article, we’ll walk through the steps to implement a Redis cache for product catalog data in a PHP 8 application.

What is Redis?

Redis is an open-source, in-memory data structure store known for its speed and flexibility. It can be used as a database, cache, and message broker, making it an excellent choice for applications that require fast access to data.

Why Use Redis for Caching?

Redis is an in-memory data structure store known for its speed and efficiency. Its ability to handle various data types makes it an ideal choice for caching scenarios. Here are some key benefits:

  • Fast Access: Retrieving data from Redis is significantly faster than querying a traditional database.
  • Reduced Database Load: By serving cached data, you minimize the number of read operations on your database.
  • Scalability: Redis can easily scale to handle increased load as your application grows.

Setting Up Your Environment

Step 1: Create a New DDEV Project

If you don’t have an existing DDEV project, you can create a new one. Open your terminal, navigate to your desired directory, and run:

mkdir my-product-catalog

cd my-product-catalog

ddev config

Follow the prompts to set up your project, ensuring that you specify PHP 8 as your environment. After configuration, start your DDEV environment:

ddev start

Step 2: Add Redis to Your DDEV Project

DDEV makes it easy to add services like Redis. To enable Redis, run:

ddev add-service redis

This command sets up Redis for your DDEV environment, making it accessible to your PHP application. If not added, alternatively you can setup using below steps

  1. Under the .ddev folder, create a file with the name docker-compose.override.yml.
  2. Add the below code into the file docker-compose.override.yml and then run ddev restart

version: '3.6'

services:

 redis:

   image: redis:latest

   container_name: day15-ddev-php-redis

   ports:

     - "6379:6379"

   networks:

     - ddev_default

   volumes:

     - redis_data:/data

volumes:

 redis_data:

   driver: local

Step 3: Access Redis

Once Redis is added, you can connect to it using the hostname redis. You can also use the Redis CLI to verify that it’s running:

ddev ssh

redis-cli ping

You should receive a response of PONG.

Step 4: Install a Redis Client for PHP

To interact with Redis in your PHP application, we will use the predis/predis library. Install it using Composer within your DDEV environment:

ddev composer require predis/predis

Implementing the Redis Cache for Product Catalog Data

Step 1: Connecting to Redis

Create a new PHP file (e.g., cache.php) in your project’s web directory. In this file, establish a connection to Redis and implement basic caching functionality:

require 'vendor/autoload.php';

use Predis\Client;

class RedisCache {

    private Client $client;

    public function __construct() {

        $this->client = new Client(['host' => 'redis', 'port' => 6379]);

    }

    public function set($key, $value, $expiration = 3600) {

        $this->client->set($key, $value);

        $this->client->expire($key, $expiration);

    }

    public function get($key) {

        return $this->client->get($key);

    }

}

Step 2: Simulating Product Catalog Data Retrieval

Next, let’s simulate a function that retrieves product catalog data. In a real application, this would typically involve querying your database. For this example, we’ll return a hardcoded array:

function fetchProductCatalog() {

    // Simulate database call

    return [

        ['id' => 1, 'name' => 'Product A', 'price' => 100],

        ['id' => 2, 'name' => 'Product B', 'price' => 200],

        ['id' => 3, 'name' => 'Product C', 'price' => 300],

    ];

}

Step 3: Implementing Caching Logic

Now, let’s implement the caching logic for the product catalog data. We’ll first check if the data is available in the cache before querying the simulated database.

function getProductCatalog(RedisCache $cache) {

    $cacheKey = 'product_catalog';

    // Try to get data from cache

    $data = $cache->get($cacheKey);

    if ($data) {

        echo "Cache hit! Retrieving product catalog from cache.\n";

        return json_decode($data, true); // Convert back to an array

    }

    // If not in cache, fetch from the "database"

    echo "Cache miss! Fetching product catalog from the database.\n";

    $data = fetchProductCatalog();

    // Store in cache

    $cache->set($cacheKey, json_encode($data)); // Cache as JSON string

    return $data;

}

// Usage example

$cache = new RedisCache();

$productCatalog = getProductCatalog($cache);

print_r($productCatalog);

Step 4: Running Your Application

To run your PHP script, access it through your web browser at http://ddev.site/cache.php, or execute it from the command line within the DDEV environment:

ddev exec php cache.php

The first call to getProductCatalog($cache) will fetch the product catalog from the simulated database, while subsequent calls will retrieve the data from the Redis cache.

Conclusion

Implementing a Redis cache for product catalog data in a PHP 8 application using DDEV is a straightforward process that can significantly enhance your application's performance. By caching frequently accessed data, you reduce database load, improve response times, and provide a better user experience.

Using DDEV simplifies the development environment setup, allowing you to focus on building efficient applications. As you continue to develop your e-commerce platform, consider leveraging Redis for additional caching and data management tasks to further optimize your application.

Thanks for reading the article, for more Science & Technology related articles read and subscribe to peoples blog articles.

Labels


Related Articles

Recent Articles

Recent Quick Read

Recent Great People

We Need Your Consent
By clicking “Accept Cookies”, you agree to the storing of cookies on your device to enhance your site navigation experience.
I Accept Cookies