Skip to content

Instantly share code, notes, and snippets.

@opengeek
Created October 16, 2010 05:00
Show Gist options
  • Save opengeek/629445 to your computer and use it in GitHub Desktop.
Save opengeek/629445 to your computer and use it in GitHub Desktop.
Snippet to flexibly cache any modElement instance
<div>
<ul>
[[!getCache? &element=`getResources` &elementClass=`modSnippet` &cache_expires=`1200` &parents=`0` &depth=`0` &limit=`2` &tpl=`ulTpl` &sortby=`RAND()`]]
</ul>
</div>
<?php
$output = '';
$properties =& $scriptProperties;
$properties['element'] = empty($element) ? '' : $element;
$properties['elementClass'] = empty($elementClass) ? 'modChunk' : $elementClass;
$properties[xPDO::OPT_CACHE_KEY] = $modx->getOption('cache_resource_key', $properties, 'default');
$properties[xPDO::OPT_CACHE_HANDLER] = $modx->getOption('cache_resource_handler', $properties, 'xPDOFileCache');
$properties[xPDO::OPT_CACHE_EXPIRES] = (integer) $modx->getOption(xPDO::OPT_CACHE_EXPIRES, $properties, 0);
$properties['cacheElementKey'] = $modx->resource->getCacheKey() . '/' . md5($modx->toJSON($properties)) . '/' . md5(implode('', $modx->request->getParameters()));
$properties['cacheOptions'] = array(
xPDO::OPT_CACHE_KEY => $properties[xPDO::OPT_CACHE_KEY],
xPDO::OPT_CACHE_HANDLER => $properties[xPDO::OPT_CACHE_HANDLER],
xPDO::OPT_CACHE_EXPIRES => $properties[xPDO::OPT_CACHE_EXPIRES],
);
$cached = false;
if ($properties['cache']) {
if ($modx->getCacheManager()) {
$cached = $modx->cacheManager->get($properties['cacheElementKey'], $properties['cacheOptions']);
}
}
if (!isset($cached['properties']) || !isset($cached['output'])) {
$elementObj = $modx->getObject($properties['elementClass'], array('name' => $properties['element']));
if ($elementObj) {
$elementObj->setCacheable(false);
if (!empty($properties['toPlaceholder'])) {
$elementObj->process($properties);
$output = $modx->getPlaceholder($properties['toPlaceholder']);
} else {
$output = $elementObj->process($properties);
}
}
if ($modx->getCacheManager()) {
$cached = array('properties' => $properties, 'output' => $output);
$modx->cacheManager->set($properties['cacheElementKey'], $cached, $properties[xPDO::OPT_CACHE_EXPIRES], $properties['cacheOptions']);
}
} else {
$properties = $cached['properties'];
$output = $cached['output'];
}
$modx->setPlaceholders($properties, $properties['namespace']);
if (!empty($properties['toPlaceholder'])) {
$modx->setPlaceholder($properties['toPlaceholder'], $output);
$output = '';
}
return $output;
?>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment