Skip to content

Instantly share code, notes, and snippets.

What would you like to do?
use Bosnadev\Repositories\Contracts\RepositoryInterface;
class MovieCacheRepo implements RepositoryInterface
public function __construct(RepositoryInterface $repo, MyCustomCache $cache, MyCustomCacheKeyGenerator $keygen)
$this->repo = $repo;
$this->cache = $cache;
$this->keygen = $keygen;
* @return \Illuminate\Support\Collection
public function findBy($attribute, $value, $columns = array('*'))
// here I will generate a cache key base on $attribute and $value
// for example $attribute = 'category' $value = 'horror'
// my keygen will generate something like: move.list.category.horror
$key = $this->keygen->getCacheKey($attribute, $value);
// if my cache exists , no need to find in database
if ($this->cache->has($key)) {
return $this->cache->fetch($key);
// no cache, look into database
$entries = $this->repo-findBy($attribute, $value, $columns);
// cache the result
$this->cache->remember($key, $entries, 30);
return $entries;
$repo = new MovieCacheRepo(new MyFakeMovieDatabaseRepository, new MyFakeCache, new MyFakeCacheKeyGenerator);
$repo->findBy('category', 'horror'); // no cache so it will queue database, cache key move.list.category.horror
$repo->findBy('category', 'horror'); // have cache so it only fetch cache data
// things getting complicate when I using Criteria
$criteria = new LengthOverTwoHours(); //$model->where('length', '>', 120);
$dbRepo = new MyFakeMovieDatabaseRepository;
$repo = new MovieCacheRepo($dbRepo, new MyFakeCache, new MyFakeCacheKeyGenerator);
//MovieCacheRepo will never know what happen in criteria
$repo->findBy('category', 'horror'); // cache key still move.list.category.horror so it will still fetch from cache
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.