Reading list Switch to dark mode

    How to use Redis for API caching in Opencart?

    Updated 20 July 2023

    Before starting the use of Redis caching for API in Opencart, you need to know about :

    1. Redis Caching
    2. API

    Redis Overview

    Redis caching stands for Remote Dictionary Server caching. It is an open-source, fast, in-memory, key-value data store. Mostly it is used for an application cache or quick response database.

    Redis is a key-value-based NoSQL database that stores data in memory, i.e. in RAM  rather than storing it in a disk or SSD.

    Redis provides several types of data structures like – strings, hashes, lists, sorted sets with range queries, sets, bitmaps, hyperloglogs, geospatial indexes, and streams.  

    You can explore more about Redis Caching and its features.

    Searching for an experienced
    Opencart Company ?
    Find out More

    API Overview

    Nowadays most web applications are built upon APIs. An API, or application programming interface, helps two programs or applications to communicate with each other by providing them with sets of definitions, functions, and tools.

    It takes the request from the user and sends it to the service provider and then again sends the result generated from the service provider to the desired user.

    Generally, we have used REST API that communicates via HTTP requests to perform standard database functions like creating, reading, updating, and deleting records.

    There are four request methods that can be used in making API:

    1. GET – Gathers the data
    2. PUT – Updates the data
    3. POST – Creates the data
    4. DELETE – Deletes the data

    Note- You can check how to create a custom REST API in Opencart.

    Implementation of Redis Caching In Opencart APIs

    While implementing of Redis caching, Either you can use the default Opencart API or can create a custom one.

    Step 1: First install Redis to your server by referring to the blog link – Using Redis Cache In Opencart

    Step 2: Navigate at path “system->library->cache->redis.php” at your project’s root directory.

    <?php
    namespace Cache;
    class Redis {
        private $expire;
        private $cache;
    
        public function __construct($expire) {
            $this->expire = $expire;
    
            $this->cache = new \Redis();
            $this->cache->pconnect(CACHE_HOSTNAME, CACHE_PORT);
        }
    
        public function get($key) {
            $data = $this->cache->get(CACHE_PREFIX . $key);
            return json_decode($data, true);
        }
    
        public function set($key,$value) {
            $status = $this->cache->set(CACHE_PREFIX . $key, json_encode($value));
            if($status){
                $this->cache->setTimeout(CACHE_PREFIX . $key, $this->expire);
            }
            return $status;
        }
    
        public function delete($key) {
            $this->cache->delete(CACHE_PREFIX . $key);
        }
    }

    This file contains three methods :

    1. SetMethod – SetMethod has two parameters one is $key and second is $value. With the use of this method, redis caching can be set with the unique key at which you want to set the data.
    2. GetMethod – GetMethod requires only the key at which you have set the data and returns the cached data.
    3. DeleteMethod – With the use of this method, set the key of the cached data that you want to delete.

    Note – Additionally, you can also set the cache expiration time.

    Step 3: Create an API in the directory “catalog/controller/api/categories.php”.

    <?php
    /**
      * Webkul Software.
      *
      * @category Webkul
      * @package Opencart Module Tutorial
      * @author Webkul
      * @license https://store.webkul.com/license.html
      */
    class ControllerApiCategories extends Controller {
    	public function getAllCategories(){
    
    		$this->load->language('api/category');
            $post = $this->request->post;
    		$json = array();
    
    		//Accepting data in json format / raw data
    
    		$raw_data = json_decode(file_get_contents("php://input"),true);
    
    		if ($raw_data) {
    			foreach ($raw_data as $key => $value) {
    				$post[$key] = $value;
    			}
    		}
         
    		if (!isset($this->session->data['api_id'])) {
    			$json['error']['warning'] = $this->language->get('error_permission');
    		
    		} else {
    
    			if(!isset($post['category_id']) || !$data['category_id'])
    			$post['category_id'] = 0;
                
    			// include redis api caching
    			$json = $this->cache->get('categories');
    			
    			if (!$json) {
    				$this->load->model('catalog/category');
    				$categories =  $this->model_catalog_category->getCategories($post['category_id']);
    
    				if ($categories) {
    					$json = array(
    						'error'	=> 0,
    						'category' => $categories
    					);
    				} else {
    					$json = array(
    						'error' => 1
    					);
    				}
    		    	$this->cache->set('categories', $json);
    		    }
    		$this->response->addHeader('Content-Type: application/json');
    		$this->response->setOutput(json_encode($json));
    	}
    }

    In the above code, we have set the key ‘categories’ for storing the categories data as cached data.

    Step 4: We’ll need more entries inside our language to display errors. So create a language file inside the directory path “catalog/language/en-gb(or any)/api/category.php

    <?php
    /**
      * Webkul Software.
      *
      * @category Webkul
      * @package Opencart Module Tutorial
      * @author Webkul
      * @license https://store.webkul.com/license.html
      */
    // Error
    $_['error_permission'] = 'Warning: You do not have permission to access the API!';

    Result of Using Redis Caching

    for access Opencart API, set the URL endpoint by entering HTTP or https://<opencart base-url>index.php?route=api/categories/getAllCategories.

    Before implementation –

    before-9

    After Implementations –

    after-3

    Here you can compare the timing of the data retrieval without using redis caching and after the use of redis caching.

    Thank You!

    If you need custom Opencart Development services then feel free to reach us and also explore our exclusive range of Opencart Extensions.

    !! Have a Great Day Ahead !!

    . . .

    Leave a Comment

    Your email address will not be published. Required fields are marked*


    Be the first to comment.

    Back to Top

    Message Sent!

    If you have more details or questions, you can reply to the received confirmation email.

    Back to Home