Reading list Switch to dark mode

    How to Use Redis for API Caching in WooCommerce Plugin

    Updated 14 August 2023

    Introduction

    Continuing our previous articles Caching in WordPress and Caching in WooCommerce Addons we’ll explore one more important caching i.e. Redis API Caching in WooCommerce. To implement this caching we’ll take the help of one famous PHP Library i.e. PHPfastecache.

    Installation

    To implement the Redis caching, please install and configure the Redis server on your system by following the official Redis installation documentation.

    To verify if the Redis server is installed and running you can open the terminal and execute the command as ‘redis-cli’ If the Redis server is configured correctly, you will enter the Command Line Interface of the Redis server. Further, you hit the command `ping` you will get the response as`PONG`

    redis-cli-ping

    redis-cli-ping-keys

    You can also see all the keys stored in the Redis server cache. Use the command `KEYS *`

    Searching for an experienced
    WordPress Company ?
    Find out More

    To make the Redis server available globally to PHP, you just need to add the redis.so shared library to the extension list of the configuration file of your PHP server. In my case, I have added the php.ini file of the Apache server. Restart of Apache server.

    redis-so-php-ini

    Verify Redis Extension

    To verify if the Redis extension is enabled, create a PHP file in the PHP installation folder and add the content as <?php phpinfo();?> Now open this file on the browser. If the Redis server is available it will be displayed something like the below screenshot.

    phpinfo

    Installing PHPfastecache

    Now to implement Redis caching in the WordPress module (plugin or theme) we need to install PHPfastcache inside the module. For this add a composer.json file and add the below lines.

    {
        "require": {
            "phpfastcache/phpfastcache": "^8.1"
        }
    }

    Now run the command composer install from the root folder. It will install the complete PHPfastcache library and other dependencies inside a new vendor folder.

    Implementation

    To implement the Redis caching in the WooCommerce plugins, we have created a class `WK_Caching_PHPFastCache` and add set methods as below.

             /**
    		 * Set the PHP fast cache contents by key and group.
    		 *
    		 * @param string $cache_key Cache key.
    		 * @param mixed  $cache_value Cache value.
    		 * @param string $cache_group Cache group.
    		 * @param int    $expiry Default 1 hour.
    		 */
    		public function set( $cache_key, $cache_value, $cache_group = 'wk', $expiry = 3600 ) {
    			$fast_key = '_wkwc_cache_' . $cache_group . '_' . $cache_key;
    
    			$driver = $this->get_driver();
    
    			if ( is_null( $this->psr_16_adapter ) ) {
    				$this->psr_16_adapter = new Psr16Adapter( $driver );
    			}
    
    			$this->psr_16_adapter->set( $fast_key, $cache_value, $expiry );
    		}
    
    		/**
    		 * Get the driver viz. Files, Redis, Predis, Mongodb -> https://www.phpfastcache.com/
    		 *
    		 * @return bool
    		 */
    		protected function get_driver() {
    			$driver = 'Files';
    
    			$res = exec( 'redis-cli ping' );
    
    			if ( 'PONG' === $res ) {
    				$driver = 'Redis';
    			}
    
    			return apply_filters( '_wkwc_get_fast_cache_driver', $driver );
    		}

    Code Explanation

    To set data in the cache we created a method `set` that accepts 4 parameters as cache key, value to cache, cache group, and the expiry time. Based on supplied cache key and cache group we created a unique cache key with some default prefix.

    Next, we create an object of the Adapter class from the PHPfastcache library. This adapter requires the driver’s name. The PHPfastecache library supports multiple drivers like ‘Files’, ‘Redis’, ‘Predis’, ‘MongoDB’ etc.

    In our scenario, we set up the Redis server and extension so after checking if the Redis server is running we supplied the ‘Redis’ driver otherwise ‘Files’ driver.

    Retrieving the data

    To get the stored data on the Redis cache server, we created a method ‘get’ as below.

           /**
    		 * Get the php fast cache contents by the key & group.
    		 *
    		 * @param string $cache_key Cache key.
    		 * @param string $cache_group Cache Group.
    		 *
    		 * @return bool|mixed
    		 */
    		public function get( $cache_key, $cache_group = 'wk' ) {
    			$fast_key = '_wkwc_cache_' . $cache_group . '_' . $cache_key;
    
    			$driver = $this->get_driver();
    
    			if ( is_null( $this->psr_16_adapter ) ) {
    				$this->psr_16_adapter = new Psr16Adapter( $driver );
    			}
    
    			WK_Caching::log( "Get PHP Fast Cache, Driver: $driver key: $fast_key, cache key: $cache_key, Cache group: $cache_group" );
    
    			$data = $this->psr_16_adapter->get( $fast_key );
    
    			return empty( $data ) ? false : $data;
    		}

    In the above code, we passed two parameters to our get method viz. ‘$cache_key’ & ‘$cache_group’ based on these params we again created the same unique key using the same prefix in the set method. And called the get method of the Adapter class.

    Conclusion: Redis for API caching in WooCommerce Add-ons

    For this article, we are concluding that Redis caching API is an efficient server caching method to provide faster results. We can implement this method for caching data to provide it on any API endpoint.

    We have successfully implemented the Redis caching API for our Multi-Vendor Marketplace for WooCommerce plugin and implementing the same in our all WooCommerce extensions with their next releases.

    Support

    For any technical assistance, please raise a ticket or reach us by mail at [email protected]

    Also, you may Hire WooCommerce Developers for your custom project development.

    . . .

    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

    Table of Content