Last active
August 29, 2015 14:17
-
-
Save timsims/d77167794cb9c0eeef90 to your computer and use it in GitHub Desktop.
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 | |
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; | |
$dbRepo->pushCriteria($criteria); | |
$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