Skip to content

Instantly share code, notes, and snippets.

@benbristow
Created November 20, 2017 16:27
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save benbristow/4753a49d4226e4a18858e8a318dfda5a to your computer and use it in GitHub Desktop.
Save benbristow/4753a49d4226e4a18858e8a318dfda5a to your computer and use it in GitHub Desktop.
Implementation of 'Rails.cache.fetch' using Stash PHP Library
<?php
use Stash\Driver\Redis;
use Stash\Pool;
class Cache {
public static function fetch(String $namespace, String $key, $expiresAfter, $callback) {
$pool = new Pool(new Redis());
$item = $pool->getItem($namespace . '/' . hash('sha256', $key));
$data = $item->get();
if($item->isMiss()) {
$item->lock();
$data = $callback();
$item->set($data);
$item->expiresAt($expiresAfter);
$pool->save($item);
}
return $data;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment