Skip to content

Implement optional disabling of caching #40

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 4 commits into from
Dec 14, 2017
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
21 changes: 21 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,27 @@ All notable changes to this project will be documented in this file.
The format is based on [Keep a Changelog](http://keepachangelog.com/en/1.0.0/)
and this project adheres to [Semantic Versioning](http://semver.org/spec/v2.0.0.html).

## [0.2.12] - 14 Dec 2017
### Added
- chainable method to disable caching of queries.

## [0.2.11] - 13 Dec 2017
### Added
- functionality to clear corresponding cache tags when model is deleted.

## [0.2.10] - 5 Dec 2017
### Fixed
- caching when using `orderByRaw()`.

## [0.2.9] - 19 Nov 2017
### Added
- test for query scopes.
- test for relationship query.

### Updated
- readme file.
- travis configuration.

## [0.2.8] - 2017-10-17
### Updated
- code with optimizations and refactoring.
Expand Down
10 changes: 10 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -49,6 +49,16 @@ abstract class BaseModel extends CachedModel
}
```

### Disabling Caching of Queries
**Recommendation: add this to all your seeder queries to avoid pulling in
cacched information when reseeding multiple times.**
You can disable a given query by using `disableCache()` in the query chain, and
it needs to be placed (anywhere) prior to the query command (`get()`, `all()`,
`find()`, etc). For example:
```php
$results = $myModel->disableCache()->all();
```

**That's all you need to do. All model queries and relationships are now
cached!**

Expand Down
2 changes: 1 addition & 1 deletion phpunit.xml
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@
convertNoticesToExceptions="true"
convertWarningsToExceptions="true"
processIsolation="false"
stopOnFailure="true"
stopOnFailure="false"
syntaxCheck="false"
bootstrap="vendor/autoload.php"
>
Expand Down
52 changes: 52 additions & 0 deletions src/CachedBuilder.php
Original file line number Diff line number Diff line change
Expand Up @@ -3,12 +3,21 @@
use GeneaLabs\LaravelModelCaching\Traits\Cachable;
use Illuminate\Database\Eloquent\Builder as EloquentBuilder;

/**
* @SuppressWarnings(PHPMD.TooManyPublicMethods)
*/
class CachedBuilder extends EloquentBuilder
{
use Cachable;

protected $isCachable = true;

public function avg($column)
{
if (! $this->isCachable) {
return parent::avg($column);
}

return $this->cache($this->makeCacheTags())
->rememberForever($this->makeCacheKey() . "-avg_{$column}", function () use ($column) {
return parent::avg($column);
Expand All @@ -17,6 +26,10 @@ public function avg($column)

public function count($columns = ['*'])
{
if (! $this->isCachable) {
return parent::count($columns);
}

return $this->cache($this->makeCacheTags())
->rememberForever($this->makeCacheKey() . "-count", function () use ($columns) {
return parent::count($columns);
Expand All @@ -25,6 +38,10 @@ public function count($columns = ['*'])

public function cursor()
{
if (! $this->isCachable) {
return collect(parent::cursor());
}

return $this->cache($this->makeCacheTags())
->rememberForever($this->makeCacheKey() . "-cursor", function () {
return collect(parent::cursor());
Expand All @@ -39,11 +56,22 @@ public function delete()
return parent::delete();
}

public function disableCache()
{
$this->isCachable = false;

return $this;
}

/**
* @SuppressWarnings(PHPMD.ShortVariable)
*/
public function find($id, $columns = ['*'])
{
if (! $this->isCachable) {
return parent::find($id, $columns);
}

return $this->cache($this->makeCacheTags())
->rememberForever($this->makeCacheKey($columns, $id), function () use ($id, $columns) {
return parent::find($id, $columns);
Expand All @@ -52,6 +80,10 @@ public function find($id, $columns = ['*'])

public function first($columns = ['*'])
{
if (! $this->isCachable) {
return parent::first($columns);
}

return $this->cache($this->makeCacheTags())
->rememberForever($this->makeCacheKey($columns) . '-first', function () use ($columns) {
return parent::first($columns);
Expand All @@ -60,6 +92,10 @@ public function first($columns = ['*'])

public function get($columns = ['*'])
{
if (! $this->isCachable) {
return parent::get($columns);
}

return $this->cache($this->makeCacheTags())
->rememberForever($this->makeCacheKey($columns), function () use ($columns) {
return parent::get($columns);
Expand All @@ -68,6 +104,10 @@ public function get($columns = ['*'])

public function max($column)
{
if (! $this->isCachable) {
return parent::max($column);
}

return $this->cache($this->makeCacheTags())
->rememberForever($this->makeCacheKey() . "-max_{$column}", function () use ($column) {
return parent::max($column);
Expand All @@ -76,6 +116,10 @@ public function max($column)

public function min($column)
{
if (! $this->isCachable) {
return parent::min($column);
}

return $this->cache($this->makeCacheTags())
->rememberForever($this->makeCacheKey() . "-min_{$column}", function () use ($column) {
return parent::min($column);
Expand All @@ -84,6 +128,10 @@ public function min($column)

public function pluck($column, $key = null)
{
if (! $this->isCachable) {
return parent::pluck($column, $key);
}

$cacheKey = $this->makeCacheKey([$column]) . "-pluck_{$column}";

if ($key) {
Expand All @@ -98,6 +146,10 @@ public function pluck($column, $key = null)

public function sum($column)
{
if (! $this->isCachable) {
return parent::sum($column);
}

return $this->cache($this->makeCacheTags())
->rememberForever($this->makeCacheKey() . "-sum_{$column}", function () use ($column) {
return parent::sum($column);
Expand Down
19 changes: 16 additions & 3 deletions src/CachedModel.php
Original file line number Diff line number Diff line change
Expand Up @@ -3,17 +3,23 @@
use GeneaLabs\LaravelModelCaching\CachedBuilder as Builder;
use Illuminate\Cache\CacheManager;
use Illuminate\Cache\TaggableStore;
use Illuminate\Cache\TaggedCache;
use Illuminate\Database\Eloquent\Builder as EloquentBuilder;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\Relation;
use LogicException;

use Illuminate\Cache\TaggedCache;
use Illuminate\Support\Collection;
use LogicException;

abstract class CachedModel extends Model
{
public function newEloquentBuilder($query)
{
if (session('genealabs-laravel-model-caching-is-disabled')) {
session()->forget('genealabs-laravel-model-caching-is-disabled');

return new EloquentBuilder($query);
}

return new Builder($query);
}

Expand Down Expand Up @@ -52,6 +58,13 @@ public function cache(array $tags = [])
return $cache;
}

public function disableCache() : self
{
session(['genealabs-laravel-model-caching-is-disabled' => true]);

return $this;
}

public function flushCache(array $tags = [])
{
$this->cache($tags)->flush();
Expand Down
2 changes: 1 addition & 1 deletion tests/Unit/CachedBuilderTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -29,7 +29,7 @@ public function setUp()
cache()->flush();
$publishers = factory(Publisher::class, 10)->create();
factory(Author::class, 10)->create()
->each(function($author) use ($publishers) {
->each(function ($author) use ($publishers) {
factory(Book::class, random_int(2, 10))->make()
->each(function ($book) use ($author, $publishers) {
$book->author()->associate($author);
Expand Down
28 changes: 25 additions & 3 deletions tests/Unit/CachedModelTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,7 @@ public function setUp()
cache()->flush();
$publishers = factory(Publisher::class, 10)->create();
factory(Author::class, 10)->create()
->each(function($author) use ($publishers) {
->each(function ($author) use ($publishers) {
factory(Book::class, random_int(2, 10))->make()
->each(function ($book) use ($author, $publishers) {
$book->author()->associate($author);
Expand Down Expand Up @@ -52,11 +52,33 @@ public function testAllModelResultsCreatesCache()
'genealabslaravelmodelcachingtestsfixturesauthor',
];

$cachedResults = cache()->tags($tags)
$cachedResults = cache()
->tags($tags)
->get($key);
$liveResults = (new UncachedAuthor)->all();
$liveResults = (new UncachedAuthor)
->all();

$this->assertEquals($authors, $cachedResults);
$this->assertEmpty($liveResults->diffAssoc($cachedResults));
}

/**
* @group test
**/
public function testScopeDisablesCaching()
{
$key = 'genealabslaravelmodelcachingtestsfixturesauthor';
$tags = ['genealabslaravelmodelcachingtestsfixturesauthor'];
$authors = (new Author)
->where("name", "Bruno")
->disableCache()
->get();

$cachedResults = cache()
->tags($tags)
->get($key);

$this->assertNull($cachedResults);
$this->assertNotEquals($authors, $cachedResults);
}
}
Loading