Skip to content

Instantly share code, notes, and snippets.

@colinmollenhour
Created August 16, 2016 20:58
Show Gist options
  • Save colinmollenhour/14ed23d029e5b991a3e31ad1fe0841d4 to your computer and use it in GitHub Desktop.
Save colinmollenhour/14ed23d029e5b991a3e31ad1fe0841d4 to your computer and use it in GitHub Desktop.
Improve Magento Layout Cache Efficiency
<?xml version="1.0" encoding="UTF-8"?>
<config>
<global>
<models>
<core>
<rewrite>
<layout_update>Template_Core_Model_Layout_Update</layout_update>
</rewrite>
</core>
</models>
</global>
</config>
<?php
/**
* This rewrite modifies the caching behavior so that the layout cache key references a SHA1
* hash of the layout XML instead of the XML itself to avoid duplication. The layout XML must
* still be generated once for each layout key, but it will not be saved if the identical
* contents already exist, saving considerable cache backend storage.
*/
class Template_Core_Model_Layout_Update extends Mage_Core_Model_Layout_Update
{
const XML_KEY_PREFIX = 'XML_';
public function loadCache()
{
if (!Mage::app()->useCache('layout')) {
return false;
}
if (!$result = Mage::app()->loadCache($this->getCacheId())) {
return false;
}
// BEGIN CODE ADDED
if (strlen($result) === 40) { // sha1
if (!$result = Mage::app()->loadCache(self::XML_KEY_PREFIX . $result)) {
return false;
}
}
// END CODE ADDED
$this->addUpdate($result);
return true;
}
public function saveCache()
{
if (!Mage::app()->useCache('layout')) {
return false;
}
$str = $this->asString();
$hash = sha1($str);
$tags = $this->getHandles();
$tags[] = self::LAYOUT_GENERAL_CACHE_TAG;
Mage::app()->saveCache($hash, $this->getCacheId(), $tags, null);
if ( ! Mage::app()->getCache()->test(self::XML_KEY_PREFIX . $hash)) {
Mage::app()->saveCache($str, self::XML_KEY_PREFIX . $hash, $tags, null);
}
return TRUE;
}
}
@colinmollenhour
Copy link
Author

For the record, this was submitted and merged into the magento-lts project.

@digitalpianism
Copy link

On PHP7 + 1.9.3 it triggers PHP Fatal error: Uncaught Error: Call to a member function addHandle() on boolean in app/code/core/Mage/Cms/Helper/Page.php:96

@digitalpianism
Copy link

My bad, was caused by a typo

@antonina11111
Copy link

screen shot 2018-03-30 at 3 53 19 pm

I need help 'maxmemory' error occured

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment