在开发的情况下,开发人员或商家的请求,他/她需要以编程方式清除/刷新缓存。如果您在 Magentoe 中以编程方式清除缓存时遇到问题,本文适合您。今天,我们将向您展示如何以编程方式清除缓存

在开始说明之前,让我提醒您一些有关 Magento 2 缓存清除的基本知识。

为什么要清除 Magento 2 中的缓存?

Magento 2 缓存清理和缓存刷新:差异

Magento 2 缓存清理/清除和 Magento 2 缓存刷新不一样。

关于缓存清理/清除: Magento 2 缓存清理/清除是删除所有启用的 Magento 相关缓存的操作。它不会清除服务器中与 Magento 无关的其他部分。

关于缓存刷新: Magento 2 缓存刷新是清理所有缓存存储的操作。与缓存清理/清除不同,此操​​作会对属于同一存储的其他存储部分产生影响。当新后端配置后缓存清理未反映前端的更改时,您可以刷新 Magento 2 中的缓存。

区分这两个动作很简单。另外,记住这一点很重要,因为如果您错误执行这两个操作,可能会导致您的商店发生意外的变化。

现在我们将了解如何在 Magento 2 中以编程方式清除/清理缓存。

如何在 Magento 2 中以编程方式清除缓存

在Helper中实现这几行代码:

<?php
use Magento\Framework\App\PageCache\Version;
use Magento\Framework\App\Cache\TypeListInterface;
use Magento\Framework\App\Cache\Frontend\Pool;
protected $cacheTypeList;
protected $cacheFrontendPool;
 
public function __construct(
    TypeListInterface $cacheTypeList, 
    Pool $cacheFrontendPool
){
    
    $this->cacheTypeList = $cacheTypeList;
    $this->cacheFrontendPool = $cacheFrontendPool;
 
}
 
public function flushCache(Version $subject)
{
  $_types = [
            'config',
            'layout',
            'block_html',
            'collections',
            'reflection',
            'db_ddl',
            'eav',
            'config_integration',
            'config_integration_api',
            'full_page',
            'translate',
            'config_webservice'
            ];
 
    foreach ($_types as $type) {
        $this->cacheTypeList->cleanType($type);
    }
    foreach ($this->cacheFrontendPool as $cacheFrontend) {
        $cacheFrontend->getBackend()->clean();
    }
}

现在调用控制器或模型flushCache()中的函数。