Skip to content

Instantly share code, notes, and snippets.

@danilopinotti
Last active December 15, 2020 18:05
Show Gist options
  • Save danilopinotti/fc848cf0a9f5e79fec4330ec1ebcc73f to your computer and use it in GitHub Desktop.
Save danilopinotti/fc848cf0a9f5e79fec4330ec1ebcc73f to your computer and use it in GitHub Desktop.
Trait to generate Model cache keys. Applicable in Models from Laravel 5+
<?php
/**
* Created by: @danilopinotti
* Inspired in Laravel Model Caching article (https://laravel-news.com/laravel-model-caching).
*/
trait CacheKeys
{
/**
* Generates a key that is updated each time Model is updated.
*
* @param string $suffix Suffix of the key
* @return string
*/
private function cacheKeyUpgradeable($suffix = '', int $version = 1)
{
if ($suffix != '') {
$suffix = str_start($suffix, ':');
}
$key = sprintf(
"%s/%s-%s%s",
$this->getTable(),
$this->getKey(),
$this->updated_at->timestamp,
$suffix
);
if ($version > 1) {
return $key.":v$version";
}
return $key;
}
/**
* Generates a key that is never updated.
*
* @param string $suffix Suffix of the key
* @return string
*/
private function cacheKey($suffix = '', int $version = 1)
{
if ($suffix != '') {
$suffix = str_start($suffix, ':');
}
$key = sprintf(
"%s/%s%s",
$this->getTable(),
$this->getKey(),
$suffix
);
if ($version > 1) {
return $key . ":v$version";
}
return $key;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment