Organizing Cache Keys In Complex Systems

İlyas Özkurt
2 min readMay 25, 2022

--

Caching is an essential part of services. When the complexity of the problem becomes too great, we may be unable to handle the cache keys. This article will show an idea about organizing complex cache keys.

Before you begin reading this essay, please review the list I've compiled below.

  • This is a PHP article.
  • Laravel was used to write this article.
  • We'll be able to keep cache keys in the same codebase.
  • Due to this, we'll be able to quickly locate cache key-related code blocks in the same codebase or 3rd party's codebase.
  • We'll make an inventory class to keep all cache keys in one place.
  • The system will generate ghost methods from the inventory class automatically.
  • We'll write a cache-broking service that supports all clear methods through the inventory class.

Creating Cache Key Inventory

To build the cache keys for the project's services or endpoints, let's make a class similar to inventory. This class will contain static methods, and each method will return a string value for the cache key it is associated with.

When we write a method in the "CacheKeysInvertory" class that returns a cache key, the system provides a ghost method that allows us to delete that cache.

Here are the two examples of methods that return cache keys.

Using "CacheKeysInventory" to Create Ghost Clear Methods

We need an auto-generation mechanism or something similar to keep code simple and maintain methods in sync. We'll use PHP's classes' __callstatic magic method.

Cache-Broking Service Endpoint

We need a service that allows 3rd parties to clear cache through our codebase to retain all caching and clearing functionalities in the same codebase.

Creating Endpoint In API

Let's create two endpoints in routes/api.php

/cache-broking endpoint

This endpoint displays all of the ways that may be used to clear key specific caches using the API.

/cache-broking/{cacheKeyMethod} endpoint

This endpoint attempts to clear the cache for specific cache keys that match the method name.

Here's the controller's source code:

Validating Clear Cache Requests That Came Over Endpoint

I created a request class that tries to check parameters for "CacheKeysInventory" class methods' ghost methods. This will validate as many parameters for ghost methods as possible.

I hope this method can help you keep your codebase well organized and high-quality.

Thanks for reading.

--

--

İlyas Özkurt
İlyas Özkurt

Written by İlyas Özkurt

Principal Developer | 14+ Years of Experience in PHP & Scalable Web Solutions

Responses (1)