No results found

Try a different search query

Popular searches:

Add to Cart

Cart

You have no purchases yet

Browse Marketplace
Original Subtotal:
Product discounts:
Quantity Discount:
Total:
View Cart
Debugging, performance and code quality

OpenCart Module Cache: How to Cache Data and When to Clear It in 3.0 and 4.1

Learn how the OpenCart module cache works in 3.0 and 4.1: the Cache library, file and Redis drivers, core cache keys, and how to clear it properly.

10 min read OC 3.0 OC 4.1

The module cache in OpenCartA free open-source CMS for online stores, written in PHP with a MySQL/MariaDB database. Everything that is not part of the core is added through extensions. More in the glossary → is a simple library $this->cache with the methods get(), set() and delete(), through which the core caches product lists, currencies, statuses and other reference data. Caching your own data through it is easy. Clearing it on time is harder: the core deletes cache by key prefix, and this only works with the file driver. Below, we look at how the cache works in 3.0 and 4.1, what the core caches itself, and how to build a module cache that does not serve stale data.

Examples are for OpenCart 4.1; in 4.0.x, model triggers and event handling differ.

How does the Cache library work?

The $this->cache object is created at startup with the driver from cache_engine and a lifetime from cache_expire in system/config/default.php. In both versions, the defaults are file and 3600 seconds. The list of drivers differs between versions: 3.0.4 has apc, file, mem, memcached and redis, 3.0.5 added apcu, and 4.1 has apcu, file, mem, memcached and redis. A comparison of cache and session drivers is in the article about session and cache.

MethodOpenCart 3.0OpenCart 4.1
get($key)in the file driver false if the key is missingin the file driver [] if the key is missing
set($key, $value)only with the general lifetimeset($key, $value, int $expire = 0), you can set a time for the key
delete($key)yesyes
clear()noyes, deletes the entire cache

The value is stored as JSON (json_encode when writing, json_decode(..., true) when reading). This has two consequences. Objects come back as associative arrays, so classes and methods are not preserved. And it is impossible to tell "an empty array is in the cache" apart from "nothing is in the cache": both look like [] in 4.1, while in 3.0 an empty array and a missing key give different results, but the if (!$data) check treats both as a miss.

How the file driver stores keys

Files are located in DIR_CACHE (by default system/storage/cache/) with the name cache.{ключ}.{час закінчення}. All characters except Latin letters, digits, dots, underscores and hyphens are removed from the key. Searching is done via glob('cache.' . $key . '.*'), and two pitfalls follow from this:

  • Deletion by prefix. delete('product') removes not only the key product but also all product.*. The core builds cache clearing on this.
  • Key collision. get('mymodule.5') will also find the file for the key mymodule.5.uk, because the pattern cache.mymodule.5.* matches both, and it returns the first one found. Do not create a key that, together with a dot, is the start of another key: put all variable parts at the end and always in the same number.

Another performance difference: in 3.0, the file driver constructor goes through all files in cache.* on every request and deletes the expired ones. On a store with thousands of keys, this is a noticeable glob on every page. In 4.1, this cleanup runs in the destructor, roughly once per hundred requests.

What does the core cache, and when does it clear?

The storefrontWhat the customer sees: the home page, categories, product page, and cart. More in the glossary → caches reference data (currencies, countries, zones, order statuses, stores, manufacturers, information pages) and some product lists.

  • OpenCart 3.0: from products, only the "latest", "popular" and "bestseller" blocks are cached (keys product.latest.*, product.popular.*, product.bestseller.* with language, store and customer groupA segment of buyers (retail, wholesale) with different prices and terms. More in the glossary →).
  • OpenCart 4.1: the getProducts() method of the catalog/product model caches the result of each query under the key 'product.' . md5($sql). That means any product list (categoryA section of the catalog that contains products. It may have subcategories. More in the glossary →, search, filter) is served from cache for up to an hour.

The cache is cleared by the admin: catalog models call $this->cache->delete() after saving for their key group, for example delete('product') in the product model of both versions, or delete('information') in the information page model. This leads to two practical situations.

Direct SQL bypasses clearing. Price imports, bulk edits or synchronizations that write to the database directly do not touch the cache. In 4.1, customers see old prices and stock levels in categories for up to an hour. After such an update, clear the cache yourself, as described in the article about the product import script.

With Redis and Memcached, the prefix does not work. Their drivers in delete() delete exactly one key (del or delete with CACHE_PREFIX . $key). delete('product') removes the key product, which nobody writes, while product.bestseller.1.0.1 or product.{md5} remain until they expire. In 4.1 with Redis, this means: the administrator changed a price, but the category still shows the old price for up to an hour. This is not a configuration error but a property of the core drivers, and modules must take it into account too.

How to cache module data correctly?

Rules that remove most problems:

  1. Module prefix in the key: mymodule., so it does not collide with the core and other modules.
  2. Everything the result depends on goes into the key: language_id, store_id, customer_group_id, currency, module settings parameters. If you forget the language, a customer on the Russian version will get names in Ukrainian.
  3. Wrap the value so you can tell an empty result from a miss: store ['data' => $result] and check isset($cached['data']).
  4. Version in the key instead of deletion by prefix. Then clearing works the same way with all drivers.

Example: module cache with a version key (OpenCart 4.1)

private function cacheKey(string $name): string {
    $version = (int)($this->cache->get('mymodule.version')['v'] ?? 0);

    return 'mymodule.' . $version . '.' . $name . '.'
        . (int)$this->config->get('config_store_id') . '.'
        . (int)$this->config->get('config_language_id') . '.'
        . (int)$this->config->get('config_customer_group_id');
}

public function getBlocks(int $module_id): array {
    $key = $this->cacheKey('blocks_' . $module_id);

    $cached = $this->cache->get($key);

    if (isset($cached['data'])) {
        return $cached['data'];
    }

    $data = $this->loadBlocks($module_id); // запити до БД

    $this->cache->set($key, ['data' => $data], 900);

    return $data;
}

Clearing the entire module cache now means incrementing the version: $this->cache->set('mymodule.version', ['v' => time()], 86400 * 365). Old keys are no longer needed and will disappear on their own when their lifetime ends. Keep the version key for a long time. If it drops out of the cache earlier, the version returns to 0 and the module simply rebuilds the cache. That is why time() as the version value is more reliable than a counter.

In 3.0, the same code works with two corrections. set() does not accept a third parameter, so all keys live cache_expire seconds (by default an hour). And get() returns false, so $this->cache->get('mymodule.version')['v'] ?? 0 must be replaced with a check for is_array().

What not to cache

  • Data of a specific customer (cart, address, personal prices) without customer_id in the key. Otherwise one customer will see another's data. It is better to keep such data in the session.
  • Error responses from external APIs. A cached error from a shipping service "breaks" calculation for an hour. Cache only successful responses, and cache errors for a few seconds at most to avoid spamming the service.
  • Large arrays. A cache of hundreds of kilobytes of JSON per key eats Redis memory and time on json_decode. Cache identifiers and recalculate the rest, or cache the finished HTML fragment of the block.

When and how to clear the module cache?

The module cache should be cleared when the data it is built from changes. Usually there are three such moments.

Saving module settings

In the save() method of the admin controllerCode that receives a request and prepares data. More in the glossary →, increment the cache version after saving. The $this->cache object in the admin is the same as on the storefront (same driver and directory), so the version is picked up immediately.

Changes to core data the module depends on

If the module caches, for example, a block of products from a category, subscribe to admin model events that change products:

  • OpenCart 3.0: admin/model/catalog/product/editProduct/after, .../addProduct/after, .../deleteProduct/after.
  • OpenCart 4.1: admin/model/catalog/product.editProduct/after, .addProduct/after, .deleteProduct/after.

The handler only increments the module's cache version. How to subscribe to model events is explained in the article about the event model, and event registration during installation is covered in the article about module install and uninstall. Direct SQL (imports, other modules) does not trigger events: for such cases, provide a "Clear cache" button in the module settings.

Installing, updating and removing the module

After a module update, the format of cached data may have changed. Incrementing the version in install() or in migrations guarantees that the new code will not read the old format. In uninstall(), clear the cache in the same way.

Manual clearing

  • OpenCart 4.1: the gear icon on the admin control panel opens Developer Options with buttons for data cache (Cache), theme (Theme) and SASS. The Cache button calls $this->cache->clear().
  • OpenCart 3.0: Developer Settings only offers clearing the theme cache (compiled Twig templates in DIR_CACHE/template/) and SASS. There is no button for the data cache. With the file driver, delete the cache.* files from DIR_CACHE; with Redis or Memcached, clear them with server tools.

Do not confuse these caches with the image cache: thumbnails are stored in image/cache/ and are cleared by deleting this directory, not with the developer buttons. The storage directory layout is described in the article about the storage directory.

If you need a cache of whole pages rather than module data, that is a separate layer with its own clearing rules. How to set it up is shown in the overview caching and PageSpeed in OpenCart.

How to check that the cache works?

  • With the file driver, look in DIR_CACHE: after opening a page, files cache.mymodule.* should appear, and the expiration time is visible in the file name.
  • Measure the method's time with and without the cache using microtime(true). If there is no difference, caching brings no benefit, and it is better to remove it. Measurement techniques are described in the article about debugging and profiling.
  • Test the module across several languages, stores and customer groups: different inputs should produce different keys.
  • If the production site uses Redis, test clearing specifically with it, not with the file driver on a local copy.

Summary

  • $this->cache stores JSON with a lifetime of cache_expire (by default 3600 seconds). In 4.1, there is a lifetime for an individual key and clear().
  • A miss in the file driver is false in 3.0 and [] in 4.1. Wrap values so you can tell an empty result apart.
  • The core clears the cache by prefix, and this works only with the file driver. With Redis and Memcached, old keys live until they expire.
  • In 4.1, all product lists are cached getProducts(), so after direct SQL the cache must be cleared manually.
  • For a module, use a prefix, language, store and group in the key, and a version for clearing.
  • Clear the cache when saving settings, on admin model events, and when updating the module.

Other materials on debugging, performance and module code quality are collected in the section "Debugging, performance and code quality".

FAQ

Can you change the cache lifetime without editing the core?
The cache_expire value is set in system/config/default.php, so you can change it only in that file or by overriding it in the application config. In 4.1, for your own module's keys, it is simpler to pass the lifetime as the third parameter of set().
Why does the old price show on the site after I change it in the admin?
Most often this is a page cache (a caching module or CDN) or Redis or Memcached, which the core's prefix-based clearing does not reach. Check which cache layer is serving the old price, and clear that layer.
Is it safe to delete the contents of the cache directory?
Yes, the core and modules will rebuild the data on the next request. The site will run a little slower for a few minutes while the cache refills.
Does OpenCart cache module settings?
No, settings are read from the setting table on every request and placed into config. A change to a setting takes effect from the next request without clearing the cache.
Was this article helpful?
Thanks for your feedback!

Related articles

Didn't find the answer?

Ask the community: OpenCart developers answer on the forum.

Ask on the forum
We use cookies

We use cookies and similar technologies to improve your experience, analyse traffic, and show personalised ads. Read our Cookie Policy for details.