Skip to content

Instantly share code, notes, and snippets.

@Lazerproof
Forked from khoatran/CachableComponent.php
Created May 12, 2020 21:41
Show Gist options
  • Save Lazerproof/221d8cb401e637e662d8dfba0d0a648a to your computer and use it in GitHub Desktop.
Save Lazerproof/221d8cb401e637e662d8dfba0d0a648a to your computer and use it in GitHub Desktop.
OctoberCMS - CachableComponent
<?php
use Cache;
use Cms\Classes\ComponentBase;
abstract class CachableComponentBase extends ComponentBase
{
/**
* Build cache configuration which is an array: ['cachedKey' => 'The cache key value', 'cachedTimeInMinutes' => 'Cached time in minutes']
* @return mixed
*/
public abstract function cacheConfig();
protected abstract function prepareData();
public function onRender()
{
$cachedConfig = $this->cacheConfig();
$key = $cachedConfig['key'];
$minutes = $cachedConfig['cachedTimeInMinutes'];
$result = Cache::remember($key, $minutes, function() {
$this->prepareData();
$output = $this->renderPartial('@default');
return $output;
});
return $result;
}
}
<?php
use \ExampleComponent;
class ExampleComponent extends CachableComponentBase
{
public function cacheConfig()
{
return ['key' => '_example_component_key',
'cachedTimeInMinutes' => 10];
}
protected function prepareData() {
//prepare your data before rendering the component
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment