如何在 magento 2 中以编程方式清理或刷新缓存?

如何在 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();
}
  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

金哥铁码

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值