Recently I was working on rendering images on a custom template. More precisely, I created a widget for inserting pictures that serve as a picture loader. And by default, the administrator has to input some parameters (width, height, alt) and if he decides, he could upload another image.
Reference for creating a widget tutorial could be seen here. The exciting part of the task was when the widget is saved on some of the Magento pages and loaded on i.e. ‘About Us’, image or images and parameter values have to be saved in the cache.
So when you visit ‘About Us’ another time, image content will be served instantly.
In this article, we’re going to save simple custom data inside the cache and load it when Magento renders the template.
Prerequisites
First of all, you will need a Magento 2 installation which is currently 2.2 version or higher. Because this implementation of the interface that we will be using for serializing data (converting to string) is not available in versions bellow 2.2. Magento will use some other preferences. So do not forget to check our How to install Magento 2, and How to create basic Magento 2 module which I highly recommend.
Creating the Block and getting the data
For the purpose of learning, we will need a layout xml file. Don’t forget to change namespace and template path with your vendor, module and file name.
<page xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" layout="1column"
xsi:noNamespaceSchemaLocation="urn:magento:framework:View/Layout/etc/page_configuration.xsd">
<body>
<referenceContainer name="content">
<block class="Inchoo\LearnCaching\Block\Cacher"
name="form"
template="Inchoo_LearnCaching::example.phtml"/>
</referenceContainer>
</body>
</page>
Of course, if your block uses dependency injection for inserting more than one additional object, then I highly recommend creating a view model.
Now, we will need a block class that will save/load data inside the cache. Of course, invoking parent constructor and inserting $context
, is a must. Another necessary object inside constructor is SerializerInterface
. Magento 2 will create
Magento\Framework\Serialize\Serializer\Json
object for you. That is all we need, for now.
Every block class is Template’s child, and Template is AbstractBlock’s child. With that pattern, all AbstractBlock children will inherit protected property $_cache
that will serve as the main object for saving or loading from cache.
Moreover, for saving data inside cache we need to go through some steps.
1. Generate data
2. Serialize data
3. Save data
or when loading the data, the algorithm should be:
1. Load data
2. Unserialize data
3. Set data
Block definition:
<?php
namespace Inchoo\LearnCaching\Block;
use Magento\Framework\Serialize\SerializerInterface;
use Magento\Framework\View\Element\Template;
class Cacher extends Template
{
private cacheId = 'IdForCachingPurposes';
/**
* @var SerializerInterface
*/
private $serializer;
/**
* Cacher constructor.
* @param Template\Context $context
* @param SerializerInterface $serialized
* @param array $data
*/
public function __construct(
Template\Context $context,
SerializerInterface $serializer,
array $data = []
) {
parent::__construct($context, $data);
$this->serializer = $serializer;
}
public function loadDataFromCache(){
$data = $this->_cache->load($this->cacheId);
if (!$data) {
$this->saveDataInCache();
return;
}
$data = $this->serializer->unserialize($data);
$this->setData($data);
};
public function saveDataInsideCache(){
$this->insertData();
$data = $this->serializer->serialize($this->getData());
$this->_cache->save($data, $this->cacheId);
};
public function insertData(){
$data = [
'id' => 1,
'first_name' => 'Roni',
'last_name' => 'Cost',
'email' => 'roni_cost@example.com'
];
$this->setData($data);
}
}
To simplify, Cacher class has hardcoded data that is used only for learning purposes. You have to insert data with collection, or maybe widget will insert that data for you, but in any case, the logic for inserting data in cache is simple. Method save($data, $uniqueId)
will save $data
in cache with unique id that could be created with some random string generator or even hard coded. And method load($this->cacheId)
will return false if data with id is not present inside cache or will return the data as a string.
So our job is to deconvert string into data, and also we have to convert data into string before saving what will be clearer in the last section of the article. The algorithm when client visits the page could look like this:
0. Get the unique cache id.
1. Load the data from the cache.
2. If data is not present
- get the data
- serialize data
- save in cache
- return
3. Otherwise
- unserialize the data
- set it with setData()
- use it
Method save()
has additional parameters. Array of tags and lifetime of the data inside cache. By default, lifetime of cache is 9999999999 in UNIX timestamp. That’s around 250 years from now.
Where does Magento 2 save the data?
Well, Magento 2 saves data inside var/cache. Open some Magento store pages without clearing the cache and look inside var/cache. There will be a bunch of mage–n directories with some weirdly named files.
That strange string in the name after last underscore (_) is unique cache Id, only converted to uppercase. So try to visit your block where Magento 2 will save data in the cache and without clearing the cache, find
mage—658_APP_IDFORCACHINGPURPOSES.
There you will find all the serialized data, which was the point after all.
How about you? Can you share some of your useful tips on saving custom data to cache? Feel free to leave the comments below and contact us if you need help to improve your Magento website performance!
The post How to save custom data in cache in Magento 2 appeared first on Inchoo.
Ecommerce
via https://www.AiUpNow.com
Lukas Scharmitzer, Khareem Sudlow