How to cache some parts of code with Lightning

Lightning provides a simple and powerful caching mechanism that can be used by devs and advanced users to make the store faster. It allows us to cache any part with 2 lines of code.

Sure, first you need to know, which code part to cache. Page Generation Metrics may help you to find out.

So, here is the simplest case. Let's say, we need to cache some method or function. Add this code line at the beginning of it:

public function getCategoryFilters($category_id) {
    if (defined('Lightning') and in_cache()) return cache();

In the end of the function add second line before returning the result:

    if (defined('Lightning')) cache($result);
    return $result;

Of course, the returned variable or expression should match written in cache(...).

In this simplest case the function result will be cached with the key that consists of class and function name and all the parameters transferred to it. In our example it may be ModelCatalogCategory->getCategoryFilters(15)

By default the cache will be used until the product table changes. Although this is the most common reason for cache clear, it doesn't fit our case. Lets say, our function depends on oc_category and oc_category_filter tables. Then the first line will look so:

     if (defined('Lightning') and in_cache(NULL, 'category category_filter')) return cache();

Take a note that tables are specified without DB_PREFIX. First parameter is an optional caching key, and NULL here says that we want to use the default scheme (ModelCatalogCategory->getCategoryFilters(15)).

Sometimes there are no tables to rely on and we need to cache result for some period of time. In this case we may specify cache time in seconds instead of tables. Here is for 5 minutes:

     if (defined('Lightning') and in_cache(NULL, 5*60)) return cache();

We can specify our own caching key (it should be string, not limited by length). That is needed if the result depends of other things except function parameters. Let's assume that our result differs of $category_id and customer group. Here it is:

     $key = $category_id . $this->customer->getGroupId();
     if (defined('Lightning') and in_cache($key, 5*60)) return cache();

Caches are cleared on Lightning cache clear and are displayed in Page Generation Metrics:

Also this code doesn't give any errors if Lightning is not installed or disabled, so it is safe to add it to shop or extensions code.

Created 2020-05-03