Sometimes Magento developers face the need to work with Magento caches programmatically. For example, when you develop your custom module, which renders some content on front-end and this content can be managed via Admin Panel. Let’s say it is cached by the Full Page Cache (FPC). In this case you will need to notify the user that one of the cache types is invalidated and should be refreshed in order to have the changes applied. You might even want to refresh the FPC automatically with each modification. Magento 2 allows this to be performed quickly and easily.
Let’s create a simple admin controller to try it in action. First of all, we’ve setup an empty “Atwix_Sample” Magento 2 module. Then added a new route with “atwix” front name.
<!-- File: app/code/Atwix/Sample/etc/adminhtml/routes.xml → <?xml version="1.0"?> <config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:App/etc/routes.xsd"> <router id="admin"> <route id="atwix" frontName="atwix"> <module name="Atwix_Sample" before="Magento_Backend" /> </route> </router> </config>
And created an index action:
<?php // File: app/code/Atwix/Sample/Controller/Adminhtml/TestCache/Index.php namespace Atwix\Sample\Controller\Adminhtml\TestCache; use Magento\Framework\View\Result\PageFactory; use Magento\Backend\Model\View\Result\Page; use Magento\Backend\App\Action\Context; use Magento\Backend\App\Action; use Magento\Framework\App\Cache\Manager as CacheManager; use Magento\Framework\App\Cache\TypeListInterface as CacheTypeListInterface; /** * Class Index */ class Index extends Action { /** * @var PageFactory */ protected $resultPageFactory; /** * @var CacheTypeListInterface */ protected $cache; /** * @var CacheManager */ protected $cacheManager; /** * @param Context $context * @param PageFactory $resultPageFactory * @param CacheTypeListInterface $cache * @param CacheManager $cacheManager */ public function __construct( Context $context, PageFactory $resultPageFactory, CacheTypeListInterface $cache, CacheManager $cacheManager ) { parent::__construct($context); $this->cache = $cache; $this->cacheManager = $cacheManager; $this->resultPageFactory = $resultPageFactory; } /** * Index action * * @return Page */ public function execute() { /** @var Page $resultPage */ $resultPage = $this->resultPageFactory->create(); $resultPage->getConfig()->getTitle()->prepend(__('Atwix Cache Manager')); /* Invalidate Full Page Cache */ $this->cache->invalidate('full_page'); return $resultPage; } }
As you can see, the $cache and $cacheManager dependencies are set in the class through its constructor:
- $cache (instance of \Magento\Framework\App\Cache\TypeList)
- $cacheManager (instance of \Magento\Framework\App\Cache\Manager)
Let’s open the created action (atwix/testCache/) and see the result.
It works, the Full Page Cache has been invalidated and we’ve got the corresponding notification message.
Magento 2 Cache Types
By default Magento 2 has the following cache types.
Cache Type Code | Cache Type | Description | Tags |
config | Configuration | Various XML configurations that were collected across modules and merged | CONFIG |
layout | Layouts | Layout building instructions | LAYOUT_GENERAL_CACHE_TAG |
block_html | Blocks HTML output | Page blocks HTML | BLOCK_HTML |
collections | Collections Data | Collection data files | COLLECTION_DATA |
reflection | Reflection Data | API interfaces reflection data | REFLECTION |
db_ddl | Database DDL operations | Results of DDL queries, such as describing tables or indexes | DB_DDL |
eav | EAV types and attributes | Entity types declaration cache | EAV |
customer_notification | Customer Notification | Customer Notification | CUSTOMER_NOTIFICATION |
full_page | Page Cache | Full page caching | FPC |
config_integration | Integrations Configuration | Integration configuration file | INTEGRATION |
config_integration_api | Integrations API Configuration | Integrations API configuration file | INTEGRATION_API_CONFIG |
translate | Translations | Translation files | TRANSLATE |
config_webservice | Web Services Configuration | REST and SOAP configurations, generated WSDL file | WEBSERVICE |
Cache TypeList
TypeList (\Magento\Framework\App\Cache\TypeList) implements several useful methods, which allow to invalidate cache, get information about invalidated cache types, get information about all declared cache types, clean cached data for specific cache type etc.
To mark specific cache type or types as invalidated you can use “invalidate” method. The only parameter that should be specified is the type code or array of type codes.
$this->cache->invalidate('full_page'); $this->cache->invalidate(['layout', 'block_html', 'full_page']);
The “getInvalidated” method allows to get array of all invalidated cache types.
$this->cache->getInvalidated();
To clean cached data for specific cache type use “cleanType” method.
$this->cache->cleanType('full_page'); $this->cache->cleanType('block_html');
If you want to get information about all declared cache types, It returns an array of data objects, where each one contains the following data:
- id – Cache type code;
- cache_type – Type label;
- description – Short description of cache type;
- tags – Cache type tags;
- status – Indicates whether cache type is enabled or not.
$availableCacheTypes = $this->cache->getTypes(); $availableCacheTypes['config_integration']->getData('id'); // 'config_integration' $availableCacheTypes['config_integration']->getData('cache_type'); // 'Integrations Configuration' $availableCacheTypes['config_integration']->getData('description'); // 'Integration configuration file' $availableCacheTypes['config_integration']->getData('tags'); // 'INTEGRATION' $availableCacheTypes['config_integration']->getData('status'); // '1' (in case the cache type is enabled)
Cache Manager
Cache Manager (\Magento\Framework\App\Cache\Manager) class is more complex and contains such useful functionality as cache types enabling/disabling, cleaning up caches and flushing cache storages.
If you want to change status (enable/disable) of some cache types you can use “setEnabled” method.
$this->cacheManager->setEnabled(['db_ddl', 'config_integration_api', 'config_integration'], false); $this->cacheManager->setEnabled(['db_ddl', 'config_integration_api', 'config_integration'], true);
When you examine Magento\Framework\App\Cache\Manager class you’ll notice two different methods: “clean” and “flush”. So let’s figure out what is the difference between them.
The first one just cleans cached data (Magento cache) – removes items from the default Magento 2 cache (var/cache) and the var/full_page cache that have a Magento tag. The \Magento\Framework\App\Cache\Manager::clean method actually calls the previously described \Magento\Framework\App\Cache\TypeList::cleanType method to clean up the cache, but accepts the array of type codes as a parameter.
$this->cacheManager->clean(['layout', 'block_html', 'full_page', 'eav']);
In case you want to clean all Magento caches, you can get the array of all available cache type codes using “getAvailableTypes” method of the Cache Manager.
$availableCacheTypes = $this->cacheManager->getAvailableTypes(); $this->cacheManager->clean($availableCacheTypes);
Let’s get back to the second method named “flush”. As you may expect it flushes specified cache storages. If your system uses an alternate cache location, any cached files used by other applications will be removed.
$this->cacheManager->flush(['layout', 'block_html', 'translate', 'customer_notification']);
As you see working with Magento 2 cache programmatically is very easy.
You may also want to read: