Skip to content

Instantly share code, notes, and snippets.

@khoatran
Last active June 24, 2020 09:12
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
  • Save khoatran/f6fadc3a70b577910fc55408d66ed8a6 to your computer and use it in GitHub Desktop.
Save khoatran/f6fadc3a70b577910fc55408d66ed8a6 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