如何在 magento 2 中以编程方式清理或刷新缓存?
在开发的情况下,开发人员或商家的请求,需要以编程方式清除/刷新缓存。如果您在 Magento2 中以编程方式清除缓存时遇到问题,本文适合您。今天,我们将向您展示如何以编程方式清除缓存。
您可以在控制器中以编程方式刷新缓存,因此不需要手动清除缓存,也不需要为特定块禁用缓存。使用下面的代码片段我们可以以编程方式清除刷新缓存。
1. 在命名空间后添加以下行
use Magento\Framework\App\Cache\TypeListInterface;
use Magento\Framework\App\Cache\Frontend\Pool;
2.定义变量
protected $cacheTypeList;
protected $cacheFrontendPool;
3.下面展示代码示例
<?php
namespace Rbj\Cache\Block;
class CacheClear extends \Magento\Framework\View\Element\Template
{
public function __construct(
\Magento\Framework\View\Element\Template\Context $context,
\Magento\Framework\App\Cache\Frontend\Pool $cacheFrontendPool,
\Magento\Framework\App\Cache\TypeListInterface $cacheTypeList,
array $data = []
) {
$this->_cacheFrontendPool = $cacheFrontendPool;
$this->_cacheTypeList = $cacheTypeList;
parent::__construct($context, $data);
}
/* Using Product id */
public function cacheClear()
{
/* get all types of cache in system */
$allTypes = array_keys($this->_cacheTypeList->getTypes());
/* Clean cached data for specific cache type */
foreach ($allTypes as $type) {
$this->_cacheTypeList->cleanType($type);
}
/* flushed the Entire cache storage from system, Works like Flush Cache Storage button click on System -> Cache Management */
foreach ($this->_cacheFrontendPool as $cacheFrontend) {
$cacheFrontend->getBackend()->clean();
}
}
}
4.调用如下函数
$productStockById = $block->cacheClear();
5.通过以下方式获取所有缓存类型的列表
$allTypes = array_keys($this->_cacheTypeList->getTypes());
6.结果如下所有缓存类型
List of cache types:
array('config','layout','block_html','collections','reflection','db_ddl',
'eav', 'customer_notification','config_integration','config_integration_api','full_page', 'translate', 'config_webservice');
7.如果你想刷新所有缓存,使用下面的方法
foreach ($this->_cacheFrontendPool as $cacheFrontend) {
$cacheFrontend->getBackend()->clean();
}