Last active
December 15, 2020 18:05
-
-
Save danilopinotti/fc848cf0a9f5e79fec4330ec1ebcc73f to your computer and use it in GitHub Desktop.
Trait to generate Model cache keys. Applicable in Models from Laravel 5+
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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