Skip to content

Commit 9f1dacb

Browse files
committed
Merge branch 'feature/add-config-to-disable-cache' into develop
2 parents 2085f89 + 3c1d023 commit 9f1dacb

19 files changed

+298
-270
lines changed

CHANGELOG.md

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,17 @@ All notable changes to this project will be documented in this file.
44
The format is based on [Keep a Changelog](http://keepachangelog.com/en/1.0.0/)
55
and this project adheres to [Semantic Versioning](http://semver.org/spec/v2.0.0.html).
66

7+
## [0.2.36] - 23 Feb 2018
8+
### Added
9+
- config setting to allow disabling of model-caching.
10+
11+
## [0.2.35] - 21 Feb 2018
12+
### Fixed
13+
- cache key generation for `find()` and `findOrFail()`.
14+
15+
### Added
16+
- caching for `paginate()`;
17+
718
## [0.2.33] - 19 Feb 2018
819
### Added
920
- unit test to make sure `Model::all()` returns a collection when only only

README.md

Lines changed: 6 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -106,13 +106,17 @@ Not only that, but it probably isn't a good idea to cache the user model anyway,
106106
since you always want to pull the most up-to-date info on it.
107107

108108
### Optional Disabling Caching of Queries
109-
**Recommendation: add this to all your seeder queries to avoid pulling in
109+
There are two methods by which model-caching can be disabled:
110+
1. Use `->disableCache()` in a query-by-query instance.
111+
2. Set `MODEL_CACHE_DISABLED=TRUE` in your `.env` file.
112+
113+
**Recommendation: use option #1 in all your seeder queries to avoid pulling in
110114
cached information when reseeding multiple times.**
111115
You can disable a given query by using `disableCache()` in the query chain, and
112116
it needs to be placed (anywhere) prior to the query command (`get()`, `all()`,
113117
`find()`, etc). For example:
114118
```php
115-
$results = $myModel->disableCache()->all();
119+
$results = $myModel->disableCache()->get();
116120
```
117121

118122
### Manual Flushing of Specific Model

composer.json

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -25,7 +25,8 @@
2525
"phpmd/phpmd": "*",
2626
"phpunit/phpunit": "*",
2727
"sebastian/phpcpd": "*",
28-
"symfony/thanks": "^1.0"
28+
"symfony/thanks": "^1.0",
29+
"predis/predis": "^1.1"
2930
},
3031
"autoload": {
3132
"psr-4": {

config/laravel-model-caching.php

Lines changed: 4 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,9 @@
11
<?php
22

33
return [
4-
'store' => env('MODEL_CACHE_STORE'),
5-
64
'cache-prefix' => '',
5+
6+
'disabled' => env('MODEL_CACHE_STORE', false),
7+
8+
'store' => env('MODEL_CACHE_STORE'),
79
];

phpunit.xml

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -9,7 +9,7 @@
99
convertWarningsToExceptions="true"
1010
printerClass="Codedungeon\PHPUnitPrettyResultPrinter\Printer"
1111
processIsolation="false"
12-
stopOnFailure="true"
12+
stopOnFailure="false"
1313
syntaxCheck="false"
1414
>
1515
<testsuites>

src/CacheKey.php

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -13,8 +13,8 @@ class CacheKey
1313
protected function getCachePrefix() : string
1414
{
1515
return "genealabs:laravel-model-caching:"
16-
. (config('genealabs:laravel-model-caching', '')
17-
? config('genealabs:laravel-model-caching', '') . ":"
16+
. (config('laravel-model-caching.cache-prefix')
17+
? config('laravel-model-caching.cache-prefix', '') . ":"
1818
: "");
1919
}
2020

src/CacheTags.php

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -18,8 +18,8 @@ public function __construct(array $eagerLoad, Model $model)
1818
protected function getCachePrefix() : string
1919
{
2020
return "genealabs:laravel-model-caching:"
21-
. (config('genealabs:laravel-model-caching', '')
22-
? config('genealabs:laravel-model-caching', '') . ":"
21+
. (config('laravel-model-caching.cache-prefix')
22+
? config('laravel-model-caching.cache-prefix', '') . ":"
2323
: "");
2424
}
2525

src/CachedBuilder.php

Lines changed: 33 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -12,7 +12,7 @@ class CachedBuilder extends EloquentBuilder
1212

1313
public function avg($column)
1414
{
15-
if (! $this->isCachable) {
15+
if (! $this->isCachable()) {
1616
return parent::avg($column);
1717
}
1818

@@ -25,7 +25,7 @@ public function avg($column)
2525

2626
public function count($columns = ['*'])
2727
{
28-
if (! $this->isCachable) {
28+
if (! $this->isCachable()) {
2929
return parent::count($columns);
3030
}
3131

@@ -38,7 +38,7 @@ public function count($columns = ['*'])
3838

3939
public function cursor()
4040
{
41-
if (! $this->isCachable) {
41+
if (! $this->isCachable()) {
4242
return collect(parent::cursor());
4343
}
4444

@@ -62,20 +62,20 @@ public function delete()
6262
*/
6363
public function find($id, $columns = ['*'])
6464
{
65-
if (! $this->isCachable) {
65+
if (! $this->isCachable()) {
6666
return parent::find($id, $columns);
6767
}
6868

6969
$arguments = func_get_args();
70-
$cacheKey = $this->makeCacheKey($columns);
70+
$cacheKey = $this->makeCacheKey(['*'], null, "-find_{$id}");
7171
$method = 'find';
7272

7373
return $this->cachedValue($arguments, $cacheKey, $method);
7474
}
7575

7676
public function first($columns = ['*'])
7777
{
78-
if (! $this->isCachable) {
78+
if (! $this->isCachable()) {
7979
return parent::first($columns);
8080
}
8181

@@ -88,7 +88,7 @@ public function first($columns = ['*'])
8888

8989
public function get($columns = ['*'])
9090
{
91-
if (! $this->isCachable) {
91+
if (! $this->isCachable()) {
9292
return parent::get($columns);
9393
}
9494

@@ -101,7 +101,7 @@ public function get($columns = ['*'])
101101

102102
public function max($column)
103103
{
104-
if (! $this->isCachable) {
104+
if (! $this->isCachable()) {
105105
return parent::max($column);
106106
}
107107

@@ -114,7 +114,7 @@ public function max($column)
114114

115115
public function min($column)
116116
{
117-
if (! $this->isCachable) {
117+
if (! $this->isCachable()) {
118118
return parent::min($column);
119119
}
120120

@@ -125,9 +125,27 @@ public function min($column)
125125
return $this->cachedValue($arguments, $cacheKey, $method);
126126
}
127127

128+
public function paginate(
129+
$perPage = null,
130+
$columns = ['*'],
131+
$pageName = 'page',
132+
$page = null
133+
) {
134+
if (! $this->isCachable()) {
135+
return parent::paginate($perPage, $columns, $pageName, $page);
136+
}
137+
138+
$arguments = func_get_args();
139+
$page = $page ?: 1;
140+
$cacheKey = $this->makeCacheKey($columns, null, "-paginate_by_{$perPage}_{$pageName}_{$page}");
141+
$method = 'paginate';
142+
143+
return $this->cachedValue($arguments, $cacheKey, $method);
144+
}
145+
128146
public function pluck($column, $key = null)
129147
{
130-
if (! $this->isCachable) {
148+
if (! $this->isCachable()) {
131149
return parent::pluck($column, $key);
132150
}
133151

@@ -141,7 +159,7 @@ public function pluck($column, $key = null)
141159

142160
public function sum($column)
143161
{
144-
if (! $this->isCachable) {
162+
if (! $this->isCachable()) {
145163
return parent::sum($column);
146164
}
147165

@@ -154,7 +172,7 @@ public function sum($column)
154172

155173
public function value($column)
156174
{
157-
if (! $this->isCachable) {
175+
if (! $this->isCachable()) {
158176
return parent::value($column);
159177
}
160178

@@ -197,7 +215,9 @@ protected function preventHashCollision(
197215
string $method
198216
) {
199217
if ($result['key'] !== $cacheKey) {
200-
cache()->tags($cacheTags)->forget($hashedCacheKey);
218+
$this->cache()
219+
->tags($cacheTags)
220+
->forget($hashedCacheKey);
201221

202222
$result = $this->retrieveCachedValue(
203223
$arguments,

src/Console/Commands/Flush.php

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -13,9 +13,11 @@ public function handle()
1313

1414
if (! $option) {
1515
cache()
16-
->store(config('laravel-model-caching:store'))
16+
->store(config('laravel-model-caching.store'))
1717
->flush();
1818

19+
$this->info("✔︎ Entire model cache has been flushed.");
20+
1921
return 0;
2022
}
2123

src/Traits/Cachable.php

Lines changed: 8 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -11,7 +11,6 @@
1111
trait Cachable
1212
{
1313
protected $isCachable = true;
14-
protected static $isCachableKey = 'genealabs:laravel-model-caching:is-disabled';
1514

1615
protected function cache(array $tags = [])
1716
{
@@ -43,8 +42,6 @@ protected function addTagsWhenCalledFromCachedBuilder(array $tags) : array
4342

4443
public function disableCache()
4544
{
46-
cache()->forever(self::$isCachableKey, true);
47-
4845
$this->isCachable = false;
4946

5047
return $this;
@@ -89,10 +86,6 @@ public static function bootCachable()
8986

9087
public static function all($columns = ['*'])
9188
{
92-
if (! cache()->get(self::$isCachableKey)) {
93-
return parent::all($columns);
94-
}
95-
9689
$class = get_called_class();
9790
$instance = new $class;
9891
$tags = [str_slug(get_called_class())];
@@ -106,12 +99,18 @@ public static function all($columns = ['*'])
10699

107100
public function newEloquentBuilder($query)
108101
{
109-
if (cache()->get(self::$isCachableKey)) {
110-
cache()->forget(self::$isCachableKey);
102+
if (! $this->isCachable()) {
103+
$this->isCachable = true;
111104

112105
return new EloquentBuilder($query);
113106
}
114107

115108
return new CachedBuilder($query);
116109
}
110+
111+
public function isCachable() : bool
112+
{
113+
return $this->isCachable
114+
&& ! config('laravel-model-caching.disabled');
115+
}
117116
}

tests/CreatesApplication.php

Lines changed: 50 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,16 +1,48 @@
11
<?php namespace GeneaLabs\LaravelModelCaching\Tests;
22

33
use GeneaLabs\LaravelModelCaching\Providers\Service as LaravelModelCachingService;
4+
use GeneaLabs\LaravelModelCaching\Tests\Fixtures\Author;
5+
use GeneaLabs\LaravelModelCaching\Tests\Fixtures\Book;
6+
use GeneaLabs\LaravelModelCaching\Tests\Fixtures\Profile;
7+
use GeneaLabs\LaravelModelCaching\Tests\Fixtures\Publisher;
8+
use GeneaLabs\LaravelModelCaching\Tests\Fixtures\Store;
49
use Orchestra\Database\ConsoleServiceProvider;
510

611
trait CreatesApplication
712
{
13+
protected $cache;
14+
815
public function setUp()
916
{
1017
parent::setUp();
1118

1219
$this->withFactories(__DIR__ . '/database/factories');
1320
$this->loadMigrationsFrom(__DIR__ . '/database/migrations');
21+
22+
$this->cache = cache()
23+
->store(config('laravel-model-caching.store'));
24+
25+
$this->cache()->flush();
26+
$publishers = factory(Publisher::class, 10)->create();
27+
factory(Author::class, 10)->create()
28+
->each(function ($author) use ($publishers) {
29+
factory(Book::class, random_int(2, 10))->make()
30+
->each(function ($book) use ($author, $publishers) {
31+
$book->author()->associate($author);
32+
$book->publisher()->associate($publishers[rand(0, 9)]);
33+
$book->save();
34+
});
35+
factory(Profile::class)->make([
36+
'author_id' => $author->id,
37+
]);
38+
});
39+
40+
$bookIds = (new Book)->all()->pluck('id');
41+
factory(Store::class, 10)->create()
42+
->each(function ($store) use ($bookIds) {
43+
$store->books()->sync(rand($bookIds->min(), $bookIds->max()));
44+
});
45+
$this->cache()->flush();
1446
}
1547

1648
/**
@@ -23,4 +55,22 @@ protected function getPackageProviders($app)
2355
ConsoleServiceProvider::class,
2456
];
2557
}
58+
59+
protected function getEnvironmentSetUp($app)
60+
{
61+
$app['config']->set('database.redis.default', [
62+
'host' => env('REDIS_HOST', '192.168.10.10'),
63+
]);
64+
$app['config']->set('database.redis.model-cache', [
65+
'host' => env('REDIS_HOST', '192.168.10.10'),
66+
'password' => env('REDIS_PASSWORD', null),
67+
'port' => env('REDIS_PORT', 6379),
68+
'database' => 1,
69+
]);
70+
$app['config']->set('cache.stores.model', [
71+
'driver' => 'redis',
72+
'connection' => 'model-cache',
73+
]);
74+
$app['config']->set('laravel-model-caching.store', 'model');
75+
}
2676
}

tests/Fixtures/BaseModel.php

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -11,7 +11,7 @@ class BaseModel extends Model
1111

1212
public function __construct($attributes = [])
1313
{
14-
config(['genealabs:laravel-model-caching' => 'test-prefix']);
14+
config(['laravel-model-caching.cache-prefix' => 'test-prefix']);
1515

1616
parent::__construct($attributes);
1717
}

0 commit comments

Comments
 (0)