Skip to content

Commit

Permalink
Merge pull request #28 from ameliaikeda/cache-prefix
Browse files Browse the repository at this point in the history
Add a prefix to the cache key.
  • Loading branch information
dwightwatson committed Aug 8, 2016
2 parents 4403e53 + f1ad348 commit 005a02b
Show file tree
Hide file tree
Showing 3 changed files with 37 additions and 3 deletions.
13 changes: 11 additions & 2 deletions README.md
Expand Up @@ -50,8 +50,17 @@ Using the remember method is super simple. Just pass the number of minutes you w

If you want to tag certain queries you can add `cacheTags('tag_name')` to your query. Please notice that cache tags are not supported by all cache drivers.

// Remember the number of users for an hour and tag it with 'user_queries'
User::remember(60)->cacheTags('user_queries')->count();
// Remember the number of users for an hour and tag it with 'user_queries'
User::remember(60)->cacheTags('user_queries')->count();

### Cache prefix

If you want a unique prefix added to the cache key for each of your queries (say, if your cache doesn't support tagging), you can add `prefix('prefix')` to your query.

// Remember the number of users for an hour and prefix the key with 'users'
User::remember(60)->prefix('users')->count();

Alternatively, you can add the ``$rememberCachePrefix` property to your model to always use that cache prefix.

#### Model wide cache tag

Expand Down
23 changes: 22 additions & 1 deletion src/Query/Builder.php
Expand Up @@ -34,6 +34,13 @@ class Builder extends \Illuminate\Database\Query\Builder
*/
protected $cacheDriver;

/**
* A cache prefix.
*
* @var string
*/
protected $cachePrefix = 'rememberable';

/**
* Execute the query as a "select" statement.
*
Expand Down Expand Up @@ -160,7 +167,7 @@ protected function getCacheInfo()
*/
public function getCacheKey()
{
return $this->cacheKey ?: $this->generateCacheKey();
return $this->cachePrefix.':'.($this->cacheKey ?: $this->generateCacheKey());
}

/**
Expand Down Expand Up @@ -208,4 +215,18 @@ protected function getCacheCallback($columns)
return $this->get($columns);
};
}

/**
* Set the cache prefix.
*
* @param string $prefix
*
* @return $this
*/
public function prefix($prefix)
{
$this->cachePrefix = $prefix;

return $this;
}
}
4 changes: 4 additions & 0 deletions src/Rememberable.php
Expand Up @@ -27,6 +27,10 @@ protected function newBaseQueryBuilder()
$builder->cacheTags($this->rememberCacheTag);
}

if (isset($this->rememberCachePrefix)) {
$builder->prefix($this->rememberCachePrefix);
}

return $builder;
}
}

0 comments on commit 005a02b

Please sign in to comment.