Skip to content

Add caching for Store API route

Add caching for Store API route

Overview

In this guide you will learn how to add a cache layer to your custom Store API route. In this example, we will add a cache layer for the ExampleRoute, which is created in the Add Store API route guide. For the cache invalidation we will write a invalidation subscriber.

Prerequisites

In order to add a cache layer for the Store API route, you first need a Store API route as base. Therefore, you can refer to the Add Store API route guide.

You also should have a look at our Adding custom complex data guide, since this guide is built upon it.

Add cache layer

As you might have learned already from the Add Store API route guide, we use abstract classes to make our routes more decoratable.

This concept is very advantageous if we now want to include a cache layer for the route. There are of course different ways to do this - but in this guide we show how we implemented it in the core.

Add cached route class

First, we create an abstract class called CachedExampleRoute which extends the AbstractExampleRoute.

In the new CachedExampleRoute some core classes are used which simplify the caching.

  • TagAwareAdapterInterface - Used to read, write and tag cache items.

  • EntityCacheKeyGenerator - Used to generate hashes for the context and/or criteria;

  • AbstractCacheTracer - Traces all system config keys that were accessed. The data is needed later for cache invalidation.

  • CacheCompressor - Provides an optimal compression of the cache entries to use as little disk space as possible.

Add cache invalidation

Cache invalidation is much harder to implement than the actual caching. Finding the right balance between too much and too little invalidation is difficult. Therefore, there is no precise guidance or documentation on when to invalidate what. What and how to invalidate depends on what has been cached. For example, the product routes in the core are always invalidated when the product is written, but also when the product is ordered and reaches the out-of-stock status. The entire cache invalidation in Shopware is controlled via events. On the one hand there is the entity written event and on the other hand the corresponding business events like ProductNoLongerAvailableEvent.