-
-
Save Danack/6eaa8bd614676b426176e694e1898b89 to your computer and use it in GitHub Desktop.
Caching wrapper
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 | |
// This is how we normally get the data. | |
class ItemRepo | |
{ | |
function getItems(string $queryParam1, int $queryParam2) { | |
// run the query against the DB. | |
} | |
} | |
// This is a wrapping version of the repo | |
class CacheItemRepo extends ItemRepo | |
{ | |
private $redis; | |
public function __construct(Redis $redis) | |
{ | |
$this->redis = $redis; | |
} | |
function getItems(string $queryParam1, int $queryParam2) | |
{ | |
$key = json_encode([ | |
'queryParam1' => $queryParam1, | |
'queryParam2' => $queryParam2, | |
]); | |
$key = sha1($key); | |
$keyname = 'itemrepo:cache:' . $key; | |
$cachedResult = $this->redis->get($keyname); | |
// Is it in the cache - yes | |
if ($cachedResult !== false) { | |
// Actually need to conver the result back from a string here. | |
return $cachedResult; | |
} | |
// not in the cache, so fetch it from the DB, | |
$data = parent::getItems($queryParam1, $queryParam2); | |
// And store it in the cache for 300 seconds | |
$this->redis->setex($keyname, 300, $data); | |
return $data; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment