当前位置: 技术文章>> magento2中的缓存公共内容以及代码示例

文章标题:magento2中的缓存公共内容以及代码示例
  • 文章分类: Magento
  • 23335 阅读
系统学习magento二次开发,推荐小册:《Magento中文全栈二次开发 》

本小册面向Magento2以上版本,书代码及示例兼容magento2.0-2.4版本。涵盖了magento前端开发,后端开发,magento2主题,magento2重写,magento2 layout,magento2控制器,magento2 block等相关内容,带领您成为magento开发技术专家。


Magento 2 中的缓存分为多种类型,其中包括缓存页面、布局、块、对象、集合和配置等。下面是一些常见的缓存类型和代码示例:

缓存页面

缓存页面是 Magento 2 中的一种缓存类型,它将整个页面缓存起来,以便下次访问时可以直接从缓存中读取。要使用 Magento 2 的页面缓存,您可以在布局文件中使用 cacheable="true" 标记。

<page xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:View/Layout/etc/page_configuration.xsd" layout="2columns-left" cacheable="true">
    <!-- 页面内容 -->
</page>

缓存块

缓存块是 Magento 2 中的另一种缓存类型,它可以将单个块的内容缓存起来,以便下次访问时可以直接从缓存中读取。要使用 Magento 2 的块缓存,您可以在块的 PHP 类中使用 cacheable="true" 标记。


例如,下面是一个使用块缓存的 PHP 类示例:



<?php
namespace Vendor\Module\Block;
use Magento\Framework\View\Element\Template;
class MyBlock extends Template
{
    /**
     * @var bool
     */
    protected $_isScopePrivate = true;
    /**
     * @return bool
     */
    protected function _isAllowed()
    {
        return $this->_authorization->isAllowed('Vendor_Module::my_resource');
    }
    /**
     * @return string
     */
    public function getCacheKeyInfo()
    {
        return [
            'VENDOR_MODULE_MYBLOCK',
            $this->_storeManager->getStore()->getId(),
            $this->_design->getDesignTheme()->getId(),
            $this->_customerSession->getCustomerGroupId(),
            intval($this->_customerSession->isLoggedIn()),
            $this->getRequest()->getParam('id'),
            $this->_scopeConfig->getValue('vendor/module/feature_enabled')
        ];
    }
}

在上面的示例中,我们可以看到 MyBlock 类继承自 Template 类,并实现了 getCacheKeyInfo() 方法和 _isScopePrivate 属性,这使得块的内容可以被缓存起来。


推荐文章