Codementor Events

Magento 2 Cache Deep Dive

Published Aug 02, 2017
Magento 2 Cache Deep Dive

Caching is used extensively in Magento. The core of caching in Magento 2 is implemented using Zend Cache. To understand concepts in Magento 2 caching, we will be looking at the Zend Framework Documentation

Key Concepts

  • Cache Frontend
  • Cache Backend
  • IDs
  • Tags

Backend and Frontend

Caching in Zend Framework is operated by frontends while cache records are stored through backend adapters (File, Sqlite, Memcache…) through a flexible system of IDs and tags.

IDs

An ID is a unique identifier (a string) that is used to identify cache records.

Tags

Tags are a way to categorize cache records. When you save a cache with the save() method, you can set an array of tags to apply for this record. Then you will be able to clean all cache records tagged with a given tag (or tags):

How do all these relate to Magento 2?

According to its documentation, Magento has default cache types found here. Each Cache Type is required to extend the TagScope Class.

Let’s take DDLCache for example, There are two constants defined:

const TYPE_IDENTIFIER='db_ddl';

const CACHE_TAG='DB_DDL’;

You remember the definition of tags? The DDLCache class states what tag is associated with it. When cache data is saved, part of the meta data includes what tag is associated with the data being saved.

So when you run bin/magento cache:clean ddl for example, all cached data with the DB_DDL tag are deleted.

You may wonder why this is important? Let’s take a look at an example of a cached data that led me into all these

Dealing with Schema/Data Versions 

Ever seen a similar message?

The following modules are outdated:
DavidUmoh_Gtpay schema: current version – 1.0.2, required version – 1.0.3
DavidUmoh_Gtpay data: current version – 1.0.2, required version – 1.0.3

This usually happens when the schema version stored in the app/etc/module.xml of a module differs from what is stored for that module in setup_module table of Magento.

The class responsible for the message is DbStatusValidator.

public function aroundDispatch(
        \Magento\Framework\App\FrontController $subject,
        \Closure $proceed,
        \Magento\Framework\App\RequestInterface $request
    ) {
        if (!$this->cache->load('db_is_up_to_date')) {
            $errors = $this->dbVersionInfo->getDbVersionErrors();
            if ($errors) {
                $formattedErrors = $this->formatErrors($errors);
                throw new \Magento\Framework\Exception\LocalizedException(
                    new \Magento\Framework\Phrase(
                        'Please upgrade your database: Run "bin/magento setup:upgrade" from the Magento root directory.'
                        . ' %1The following modules are outdated:%2%3',
                        [PHP_EOL, PHP_EOL, implode(PHP_EOL, $formattedErrors)]
                    )
                );
            } else {
                $this->cache->save('true', 'db_is_up_to_date');
            }
        }
        return $proceed($request);
    }

On line 54  You can see that cached data is loaded using the unique id ‘db_is_up_to_date’. The Concrete Cache class as seen below is the Config Cache class.

When you take a look at the Magento\Framework\App\Cache\Type\Config  class, you see that the Cache Tag defined for that class is ‘CONFIG’ and the type identifier is ‘config’. That corresponds to the config cache type in Magento.

class Config extends TagScope implements CacheInterface
{
   /**
    * Cache type code unique among all cache types
    */
   const TYPE_IDENTIFIER = 'config';
   /**
    * Cache tag used to distinguish the cache type from all other cache
    */
   const CACHE_TAG = 'CONFIG';
   /**
    * @var \Magento\Framework\App\Cache\Type\FrontendPool
    */
   private $cacheFrontendPool;

If for any reason you do not want that cached data to be removed during an operation, then you should avoid clearing the config cache until you need to or write data to cache using the example from the image above.

In the next blog post, I’ll show an example of changing the cache type used in a particular class.

Discover and read more posts from David
get started
post commentsBe the first to share your opinion
Bryan "BJ" Hoffpauir, Jr.
7 years ago

David - this was a really well written and informative deep dive in to the caching layer of Magento 2 - thanks for sharing it with us!

David
7 years ago

Thanks Bryan. I am glad you found the post helpful.

Show more replies