Magento 2: Get, Clean and Flush Cache Programmatically

This article shows how you can get the list of all Cache Types in Magento and how you can clean and flush those Cache Types in Magento.

Cache Types in Magento

Magento has the following cache types:

Configuration (config)
Commerce collects configuration from all modules, merges it, and saves the merged result to the cache. This cache also contains store-specific settings stored in the file system and database. Clean or flush this cache type after modifying configuration files.

Layout (layout)
Compiled page layouts (that is, the layout components from all components). Clean or flush this cache type after modifying layout files.

Block HTML output (block_html)
HTML page fragments per block. Clean or flush this cache type after modifying the view layer.

Collections data (collections)
Results of database queries. If necessary, Commerce cleans up this cache automatically, but third-party developers can put any data in any segment of the cache. Clean or flush this cache type if your custom module uses logic that results in cache entries that Commerce cannot clean.

DDL (db_ddl)
Database schema. If necessary, Commerce cleans up this cache automatically, but third-party developers can put any data in any segment of the cache. Clean or flush this cache type after you make custom changes to the database schema. (In other words, updates that Commerce does not make itself.) One way to update the database schema automatically is using the magento setup:db-schema:upgrade command.

Compiled Config (compiled_config)
Compilation configuration

Entity attribute value (eav)
Metadata related to EAV attributes (for example, store labels, links to related PHP code, attribute rendering, search settings, and so on). You should not typically need to clean or flush this cache type.

Page cache (full_page)
Generated HTML pages. If necessary, Commerce cleans up this cache automatically, but third-party developers can put any data in any segment of the cache. Clean or flush this cache type after modifying code level that affects HTML output. It is recommended to keep this cache enabled because caching HTML improves performance significantly.

Reflection (reflection)
Removes a dependency between the Webapi module and the Customer module.

Translations (translate)
After merging translations from all modules, the merger cache will be cleaned.

Integration configuration (config_integration)
Compiled integrations. Clean or flush this cache after changing or adding integrations.

Integration API configuration (config_integration_api)
Compiled integration APIs configuration of the Store’s Integrations.

Web services configuration (config_webservice)
Caching the Web API Structure.

Customer Notification (customer_notification)
Temporary notifications that appear in the user interface.

Get List of All Cache Types

List of all declared cache types can be fetched using different class interfaces.

Get list of all Cache Types using CacheConfigInterface

The main class interface to get the cache types configuration is \Magento\Framework\Cache\ConfigInterface.


use Magento\Framework\Cache\ConfigInterface as CacheConfig;

class YourClassName
{
    /**
     * @var CacheConfig
     */
    protected $cacheConfig;

    /**
     ...
     * @param CacheConfig $cacheConfig
     */
    public function __construct(
        ...
        CacheConfig $cacheConfig
    ) {
        ...
        $this->cacheConfig = $cacheConfig;
    }

    /**
     * Get information about all declared cache types
     *
     * @return array
     */
    public function getCacheTypeList()
    {
        return $this->cacheConfig->getTypes();
    }

    /**
     * Get configuration of specified cache type
     *
     * @param string $typeCode
     * @return array
     */
    public function getCacheType($typeCode)
    {
        return $this->cacheConfig->getType($typeCode);
    }
}

OUTPUT

Output of call the function getCacheTypeList().


Array
(
    [config] => Array
        (
            [name] => config
            [translate] => label,description
            [instance] => Magento\Framework\App\Cache\Type\Config
            [label] => Configuration
            [description] => Various XML configurations that were collected across modules and merged
        )

    [layout] => Array
        (
            [name] => layout
            [translate] => label,description
            [instance] => Magento\Framework\App\Cache\Type\Layout
            [label] => Layouts
            [description] => Layout building instructions
        )

    [block_html] => Array
        (
            [name] => block_html
            [translate] => label,description
            [instance] => Magento\Framework\App\Cache\Type\Block
            [label] => Blocks HTML output
            [description] => Page blocks HTML
        )

    [collections] => Array
        (
            [name] => collections
            [translate] => label,description
            [instance] => Magento\Framework\App\Cache\Type\Collection
            [label] => Collections Data
            [description] => Collection data files
        )

    [reflection] => Array
        (
            [name] => reflection
            [translate] => label,description
            [instance] => Magento\Framework\App\Cache\Type\Reflection
            [label] => Reflection Data
            [description] => API interfaces reflection data
        )

    [db_ddl] => Array
        (
            [name] => db_ddl
            [translate] => label,description
            [instance] => Magento\Framework\DB\Adapter\DdlCache
            [label] => Database DDL operations
            [description] => Results of DDL queries, such as describing tables or indexes
        )

    [compiled_config] => Array
        (
            [name] => compiled_config
            [translate] => label,description
            [instance] => Magento\Framework\App\Interception\Cache\CompiledConfig
            [label] => Compiled Config
            [description] => Compilation configuration
        )

    [eav] => Array
        (
            [name] => eav
            [translate] => label,description
            [instance] => Magento\Eav\Model\Cache\Type
            [label] => EAV types and attributes
            [description] => Entity types declaration cache
        )

    [customer_notification] => Array
        (
            [name] => customer_notification
            [translate] => label,description
            [instance] => Magento\Customer\Model\Cache\Type\Notification
            [label] => Customer Notification
            [description] => Customer Notification
        )

    [config_integration] => Array
        (
            [name] => config_integration
            [translate] => label,description
            [instance] => Magento\Integration\Model\Cache\Type
            [label] => Integrations Configuration
            [description] => Integration configuration file
        )

    [config_integration_api] => Array
        (
            [name] => config_integration_api
            [translate] => label,description
            [instance] => Magento\Integration\Model\Cache\TypeIntegration
            [label] => Integrations API Configuration
            [description] => Integrations API configuration file
        )

    [full_page] => Array
        (
            [name] => full_page
            [translate] => label,description
            [instance] => Magento\PageCache\Model\Cache\Type
            [label] => Page Cache
            [description] => Full page caching
        )

    [target_rule] => Array
        (
            [name] => target_rule
            [translate] => label,description
            [instance] => Magento\TargetRule\Model\Cache\Index
            [label] => Target Rule
            [description] => Target Rule Index
        )

    [config_webservice] => Array
        (
            [name] => config_webservice
            [translate] => label,description
            [instance] => Magento\Webapi\Model\Cache\Type\Webapi
            [label] => Web Services Configuration
            [description] => REST and SOAP configurations, generated WSDL file
        )

    [translate] => Array
        (
            [name] => translate
            [translate] => label,description
            [instance] => Magento\Framework\App\Cache\Type\Translate
            [label] => Translations
            [description] => Translation files
        )

)

OUTPUT

Output of getCacheType($typeCode) function where $typeCode is set as block_html.


Array
(
    [name] => block_html
    [translate] => label,description
    [instance] => Magento\Framework\App\Cache\Type\Block
    [label] => Blocks HTML output
    [description] => Page blocks HTML
)

Get list of all Cache Types using CacheTypesListInterface

The other class interface to get the cache types configuration is \Magento\Framework\App\Cache\TypeListInterface.
The implementation class of this interface also returns the cache status and the cache tag.


use Magento\Framework\App\Cache\TypeListInterface as CacheTypeList;

class YourClassName
{
    /**
     * @var CacheTypeList
     */
    protected $cacheTypeList;

    /**
     ...
     * @param CacheTypeList $cacheTypeList
     */
    public function __construct(
        ...
        CacheTypeList $cacheTypeList
    ) {
        ...
        $this->cacheTypeList = $cacheTypeList;
    }

    /**
     * Get information about all declared cache types
     *
     * @return array
     */
    public function getCacheTypeList()
    {
        return $this->cacheTypeList->getTypes();
    }
}

OUTPUT:


Array
(
    [config] => Magento\Framework\DataObject Object
        (
            [_data:protected] => Array
                (
                    [id] => config
                    [cache_type] => Configuration
                    [description] => Various XML configurations that were collected across modules and merged
                    [tags] => CONFIG
                    [status] => 1
                )

        )

    [layout] => Magento\Framework\DataObject Object
        (
            [_data:protected] => Array
                (
                    [id] => layout
                    [cache_type] => Layouts
                    [description] => Layout building instructions
                    [tags] => LAYOUT_GENERAL_CACHE_TAG
                    [status] => 1
                )

        )

    [block_html] => Magento\Framework\DataObject Object
        (
            [_data:protected] => Array
                (
                    [id] => block_html
                    [cache_type] => Blocks HTML output
                    [description] => Page blocks HTML
                    [tags] => BLOCK_HTML
                    [status] => 1
                )

        )

    [collections] => Magento\Framework\DataObject Object
        (
            [_data:protected] => Array
                (
                    [id] => collections
                    [cache_type] => Collections Data
                    [description] => Collection data files
                    [tags] => COLLECTION_DATA
                    [status] => 1
                )

        )

    [reflection] => Magento\Framework\DataObject Object
        (
            [_data:protected] => Array
                (
                    [id] => reflection
                    [cache_type] => Reflection Data
                    [description] => API interfaces reflection data
                    [tags] => REFLECTION
                    [status] => 1
                )

        )

    [db_ddl] => Magento\Framework\DataObject Object
        (
            [_data:protected] => Array
                (
                    [id] => db_ddl
                    [cache_type] => Database DDL operations
                    [description] => Results of DDL queries, such as describing tables or indexes
                    [tags] => DB_DDL
                    [status] => 1
                )

        )

    [compiled_config] => Magento\Framework\DataObject Object
        (
            [_data:protected] => Array
                (
                    [id] => compiled_config
                    [cache_type] => Compiled Config
                    [description] => Compilation configuration
                    [tags] => COMPILED_CONFIG
                    [status] => 1
                )

        )

    [eav] => Magento\Framework\DataObject Object
        (
            [_data:protected] => Array
                (
                    [id] => eav
                    [cache_type] => EAV types and attributes
                    [description] => Entity types declaration cache
                    [tags] => EAV
                    [status] => 1
                )

        )

    [customer_notification] => Magento\Framework\DataObject Object
        (
            [_data:protected] => Array
                (
                    [id] => customer_notification
                    [cache_type] => Customer Notification
                    [description] => Customer Notification
                    [tags] => CUSTOMER_NOTIFICATION
                    [status] => 1
                )

        )

    [config_integration] => Magento\Framework\DataObject Object
        (
            [_data:protected] => Array
                (
                    [id] => config_integration
                    [cache_type] => Integrations Configuration
                    [description] => Integration configuration file
                    [tags] => INTEGRATION
                    [status] => 1
                )

        )

    [config_integration_api] => Magento\Framework\DataObject Object
        (
            [_data:protected] => Array
                (
                    [id] => config_integration_api
                    [cache_type] => Integrations API Configuration
                    [description] => Integrations API configuration file
                    [tags] => INTEGRATION_API_CONFIG
                    [status] => 1
                )

        )

    [full_page] => Magento\Framework\DataObject Object
        (
            [_data:protected] => Array
                (
                    [id] => full_page
                    [cache_type] => Page Cache
                    [description] => Full page caching
                    [tags] => FPC
                    [status] => 1
                )

        )

    [target_rule] => Magento\Framework\DataObject Object
        (
            [_data:protected] => Array
                (
                    [id] => target_rule
                    [cache_type] => Target Rule
                    [description] => Target Rule Index
                    [tags] => TARGET_RULE
                    [status] => 1
                )

        )

    [config_webservice] => Magento\Framework\DataObject Object
        (
            [_data:protected] => Array
                (
                    [id] => config_webservice
                    [cache_type] => Web Services Configuration
                    [description] => REST and SOAP configurations, generated WSDL file
                    [tags] => WEBSERVICE
                    [status] => 1
                )

        )

    [translate] => Magento\Framework\DataObject Object
        (
            [_data:protected] => Array
                (
                    [id] => translate
                    [cache_type] => Translations
                    [description] => Translation files
                    [tags] => TRANSLATE
                    [status] => 1
                )

        )

)

Clean and Flush Cache

Cache Clean

Clean Cache using CacheTypeList class


use Magento\Framework\App\Cache\TypeListInterface as CacheTypeList;

class YourClassName
{
    /**
     * @var CacheTypeList
     */
    protected $cacheTypeList;

    /**
     ...
     * @param CacheTypeList $cacheTypeList
     */
    public function __construct(
        ...
        CacheTypeList $cacheTypeList
    ) {
        ...
        $this->cacheTypeList = $cacheTypeList;
    }

    /**
     * Clean Cache
     */
    public function cleanCache()
    {
        /**
         * Get the list of all cache type code
         *
         * $allCacheTypes array example:
         * [
         *   'config',
         *   'layout',
         *   'block_html',
         *   'collections',
         *   'reflection',
         *   'db_ddl',
         *   'compiled_config',
         *   'eav',
         *   'customer_notification',
         *   'config_integration',
         *   'config_integration_api',
         *   'full_page',
         *   'target_rule',
         *   'config_webservice',
         *   'translate'
         * ];
         */ 
        $allCacheTypes = array_keys($this->cacheTypeList->getTypes());

        foreach ($allCacheTypes as $type) {
            $this->cacheTypeList->cleanType($type);
        }
    }
}

Clean Cache using CacheManager class


use Magento\Framework\App\Cache\Manager as CacheManager;

class YourClassName
{
    /**
     * @var CacheManager
     */
    protected $cacheManager;

    /**
     ...
     * @param CacheManager $cacheManager
     */
    public function __construct(
        ...
        CacheManager $cacheManager
    ) {
        ...
        $this->cacheManager = $cacheManager;
    }

    /**
     * Clean Cache
     */
    public function cleanCache()
    {
        /*
        $cacheTypes = [
            'config',
            'layout',
            'block_html',
            'collections',
            'reflection',
            'db_ddl',
            'compiled_config',
            'eav',
            'customer_notification',
            'config_integration',
            'config_integration_api',
            'full_page',
            'target_rule',
            'config_webservice',
            'translate'
        ];
        */
        $cacheTypes = $this->cacheManager->getAvailableTypes();
        $this->cacheManager->clean($cacheTypes);
    }
}

Flush Cache

Flush Cache using CacheFrontendPool class


use Magento\Framework\App\Cache\Frontend\Pool as CacheFrontendPool;

class YourClassName
{
    /**
     * @var CacheFrontendPool
     */
    protected $cacheFrontendPool;

    /**
     ...
     * @param CacheFrontendPool $cacheFrontendPool
     */
    public function __construct(
        ...
        CacheFrontendPool $cacheFrontendPool
    ) {
        ...
        $this->cacheFrontendPool = $cacheFrontendPool;
    }

    /**
     * Flush Cache
     */
    public function flushCache()
    {
        foreach ($this->cacheFrontendPool as $cacheFrontend) {
            $cacheFrontend->getBackend()->clean();
        }
    }
}

Flush Cache using CacheManager class


use Magento\Framework\App\Cache\Manager as CacheManager;

class YourClassName
{
    /**
     * @var CacheManager
     */
    protected $cacheManager;

    /**
     ...
     * @param CacheManager $cacheManager
     */
    public function __construct(
        ...
        CacheManager $cacheManager
    ) {
        ...
        $this->cacheManager = $cacheManager;
    }

    /**
     * Clean Cache
     */
    public function cleanCache()
    {
        /*
        $cacheTypes = [
            'config',
            'layout',
            'block_html',
            'collections',
            'reflection',
            'db_ddl',
            'compiled_config',
            'eav',
            'customer_notification',
            'config_integration',
            'config_integration_api',
            'full_page',
            'target_rule',
            'config_webservice',
            'translate'
        ];
        */
        $cacheTypes = $this->cacheManager->getAvailableTypes();
        $this->cacheManager->flush($cacheTypes);
    }
}

References:
Manage the Cache

Hope this helps. Thanks.