Magento 2: Enable/Disable Cache Programmatically

This article shows how you can enable or disable Magento Cache Programmatically.

For this purpose, we will be using \Magento\Framework\App\Cache\Manager 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;
    }

    /**
     * @param array $types
     * @param bool $isEnabled
     * @return array List of types with changed status
     */
    public function changeCacheStatus(array $types, $isEnabled)
    {
        return $this->cacheManager->setEnabled($types, $isEnabled);
    }
}

All Cache Types can be enabled/disabled. Or, particular cache types can be passed to enable/disable.


// Disable All Cache Types
$cacheTypes = $this->cacheManager->getAvaiableTypes();
$this->cacheManager->setEnabled($cacheTypes, false);

// Enable All Cache Types
$cacheTypes = $this->cacheManager->getAvaiableTypes();
$this->cacheManager->setEnabled($cacheTypes, false);

// Disable Particular Cache Types
$cacheTypes = [
    'layout',
    'block_html'
];
$this->cacheManager->setEnabled($cacheTypes, false);

// Get status of all cache types
$this->cacheManager->getStatus();

Hope this helps. Thanks.