系统学习magento二次开发,推荐小册:《Magento中文全栈二次开发 》
本小册面向Magento2以上版本,书代码及示例兼容magento2.0-2.4版本。涵盖了magento前端开发,后端开发,magento2主题,magento2重写,magento2 layout,magento2控制器,magento2 block等相关内容,带领您成为magento开发技术专家。
在 Magento 2 中,可以通过创建自定义的缓存类型来缓存您的应用程序数据。下面是一个示例,演示如何在 Magento 2 中创建自定义缓存类型:
<?php
namespace Namespace\Module\Model\Cache\Type;
use Magento\Framework\App\Cache\Type\FrontendPool;
use Magento\Framework\Cache\Frontend\Decorator\TagScope;
class CustomCacheType extends TagScope
{
const CACHE_TYPE = 'custom_cache_type';
public function __construct(FrontendPool $cacheFrontendPool)
{
parent::__construct($cacheFrontendPool->get(self::CACHE_TYPE), self::CACHE_TYPE);
}
}在上面的示例中,我们创建了一个名为 CustomCacheType 的自定义缓存类型,并继承了 TagScope 类来支持标签。
我们定义了 CACHE_TYPE 常量来表示缓存类型的名称。
我们在 __construct() 方法中获取缓存实例,并将其传递给 TagScope 类的构造函数。
接下来,我们需要在 di.xml 文件中注册缓存类型:
<config> <type name="Namespace\Module\Model\Cache\Type\CustomCacheType"> <arguments> <argument name="cacheFrontendPool" xsi:type="object">Magento\Framework\App\Cache\Type\FrontendPool</argument> </arguments> </type> </config>
在上面的示例中,我们将 Namespace\Module\Model\Cache\Type\CustomCacheType 类型注册为缓存类型,并传递了 cacheFrontendPool 依赖项。
现在,我们可以在代码中使用我们的自定义缓存类型。例如,以下是一个示例,演示如何在 Magento 2 中使用自定义缓存类型:
<?php
namespace Namespace\Module\Block;
use Namespace\Module\Model\Cache\Type\CustomCacheType;
class CustomBlock extends \Magento\Framework\View\Element\Template
{
protected $cacheType;
public function __construct(
\Magento\Framework\View\Element\Template\Context $context,
CustomCacheType $cacheType,
array $data = []
) {
parent::__construct($context, $data);
$this->cacheType = $cacheType;
}
protected function _toHtml()
{
$cacheKey = 'my_cache_key';
$cacheData = $this->cacheType->load($cacheKey);
if (!$cacheData) {
$cacheData = 'My cached data';
$this->cacheType->save($cacheData, $cacheKey, [], 86400); // 缓存时间为一天
}
return $cacheData;
}
}在上面的示例中,我们在 __construct() 方法中注入了我们的自定义缓存类型 CustomCacheType。在 _toHtml() 方法中,我们使用 load() 方法来从缓存中获取数据,并使用 save() 方法将数据保存到缓存中。
当缓存启用时,Magento 2 会在页面加载时自动缓存块。Magento 2 会检查缓存是否存在并且没有过期,如果找到了缓存,则直接从缓存中获取内容,否则会生成新的内容并将其保存到缓存中以备下次使用