Skip to content

Instantly share code, notes, and snippets.

@alecbedzir
Last active December 24, 2015 15:59
Show Gist options
  • Select an option

  • Save alecbedzir/6825215 to your computer and use it in GitHub Desktop.

Select an option

Save alecbedzir/6825215 to your computer and use it in GitHub Desktop.
Caching models in magento (possible way). ----- Model after being grabbed from cache is read-only. ----- Note, that once being cached, model is not updated any more in the cache (only if cache is flushed), so even if in DB data is updated - application will still use old data from model cache. ----- Possible improvements: (1) use getSingleton in…
<?php
const LOAD_CACHED_MODEL_KEY_PREFIX = 'cached_model';
/* Usage: */
$specificCmsBlock = Mage::helper('customization')->loadCachedReadOnlyModel('cmsBlockId', 'cms/block');
/**
* Caching model in Magento.
* After being fetched from cache model is supposed to be read-only
* Not tested yet what happens if save() is triggered on model after is is gotten from cache
*/
public function loadCachedReadOnlyModel($idToLoad, $modelClass)
{
$cacheKey = self::LOAD_CACHED_MODEL_KEY_PREFIX . $modelClass . $idToLoad;
$cachedModelData = Mage::app()->getCache()->load($cacheKey);
if (!empty($cachedModelData)) {
$cachedModel = Mage::getModel($modelClass);
$cachedModel->setData(Zend_Json::decode($cachedModelData));
} else {
$cachedModel = Mage::getModel($modelClass)->load($idToLoad);
if ($cachedModel->getId()) {
$cachedModelData = $cachedModel->toJson();
Mage::app()->getCache()->save($cachedModelData, $cacheKey);
}
}
return $cachedModel;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment