I have created a custom cache in a custom module to which I am able to read and write through an observer. However, when I'm trying to get the stored data in a block file I am getting an empty response.
Here is my code:
Block/Calendar.php
namespace Myextension\Functionality\Block;
use Magento\Framework\View\Element\Template;
use \Magento\Framework\App\Cache;
class Calendar extends \Magento\Framework\View\Element\Template
{
protected $cache;
public function __construct(Template\Context $context,\Magento\Framework\App\Cache $cache, array $data = array())
{
parent::__construct($context, $data);
// set constructor values
$this->cache = $cache;
}
/**
* @return array
*/
public function getCountriesList()
{
$stores_cache = unserialize($this->cache->load("STORES_CACHE_TAG"));
return $stores_cache;
}
}
And here is the observer which is able to read/write to the cache successfully.
namespace Myextension\Functionality\Observer\Adminhtml;
class CacheRefreshType implements \Magento\Framework\Event\ObserverInterface
{
protected $scopeConfig;
protected $cache;
protected $storeManager;
/**
* CacheRefreshType constructor.
* @param \Magento\Framework\App\Config\ScopeConfigInterface $scopeConfig
*/
public function __construct(
\Magento\Framework\App\Config\ScopeConfigInterface $scopeConfig,
\Magento\Framework\App\Cache $cache,
\Magento\Store\Model\StoreManagerInterface $storeManager
)
{
// set constuct variables
$this->scopeConfig = $scopeConfig;
$this->cache = $cache;
$this->storeManager = $storeManager;
}
private function refreshStoresCache() {
// get list of stores
$storeManagerDataList = $this->storeManager->getWebsites();
// init empty array of stores
$stores = [];
// for each store
foreach ($storeManagerDataList as $key => $value) {
// append store information
$stores[$key] = [
"label" => $value["name"],
"code"=>$value["code"]
];
}
// save cache
$this->cache->save(serialize($stores), "stores_cache_tag",array("STORES_CACHE_TAG"), 99999);
$stores_cache = unserialize($this->cache->load("STORES_CACHE_TAG"));
}
I am really thankful for any help!