Skip to content

Commit 802290d

Browse files
committed
Merge remote-tracking branch 'remotes/origin/master' into feature/add-nova-tests
# Conflicts: # composer.json
2 parents bdf2794 + 6be9445 commit 802290d

File tree

82 files changed

+1717
-165
lines changed

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

82 files changed

+1717
-165
lines changed

.github/FUNDING.yml

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,7 @@
11
# These are supported funding model platforms
22

3-
github: # Replace with up to 4 GitHub Sponsors-enabled usernames e.g., [user1, user2]
4-
patreon: mikebronner
3+
github: [mikebronner]
4+
patreon: #mikebronner
55
open_collective: # Replace with a single Open Collective username
66
ko_fi: # Replace with a single Ko-fi username
77
tidelift: # Replace with a single Tidelift platform-name/package-name e.g., npm/babel

.github/stale.yml

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -11,6 +11,7 @@ exemptLabels:
1111
- enhancement
1212
- unconfirmed bug
1313
- future development
14+
- documentation
1415
# Label to use when marking an issue as stale
1516
staleLabel: wontfix
1617
# Comment to post when marking an issue as stale. Set to `false` to disable

.gitignore

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2,3 +2,4 @@
22
/vendor
33
composer.lock
44
.phpunit.result.cache
5+
phpunit.xml

.travis.yml

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -16,19 +16,19 @@ env:
1616

1717
matrix:
1818
include:
19-
- php: 7.2
2019
- php: 7.3
20+
- php: 7.4
2121

2222
before_script:
2323
- travis_retry composer self-update
2424
- travis_retry composer config --global github-protocols https
2525
- travis_retry composer install --no-interaction --prefer-source
2626
- psql -c "CREATE DATABASE testing;" -U postgres
27-
- psql -c "CREATE USER mike WITH PASSWORD '';" -U postgres
27+
- psql -c "CREATE USER homestead WITH PASSWORD 'secret';" -U postgres
2828

2929
script:
3030
- mkdir -p build/logs
31-
- php vendor/bin/phpunit -c phpunit.xml --coverage-clover build/logs/clover.xml
31+
- php vendor/bin/phpunit -c phpunit.xml.dist --coverage-clover build/logs/clover.xml
3232

3333
after_success:
3434
- travis_retry php vendor/bin/php-coveralls -v

.vscode/launch.json

Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,17 @@
1+
{
2+
// Use IntelliSense to learn about possible attributes.
3+
// Hover to view descriptions of existing attributes.
4+
// For more information, visit: https://go.microsoft.com/fwlink/?linkid=830387
5+
"version": "0.2.0",
6+
"configurations": [
7+
{
8+
"name": "Listen for XDebug",
9+
"type": "php",
10+
"request": "launch",
11+
"port": 9000,
12+
"pathMappings": {
13+
"/home/vagrant/Sites/ens": "/Users/mike/Developer/Sites/ens"
14+
}
15+
}
16+
]
17+
}

CHANGELOG.md

Lines changed: 31 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,37 @@ 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.8.1] - 2020-04-09
8+
### Fixed
9+
- `jsonContains()` with array values. Thanks @dmason30!
10+
- `truncate()` to flush cache. Thanks @dmason30!
11+
12+
## [0.8.0] - 2020-02-29
13+
### Added
14+
- Laravel 7 compatibility.
15+
16+
## [0.7.4] - 2019-12-22
17+
### Added
18+
- documentation to explain that database transactions are currently not supported.
19+
- compatibility with binary UUIDs. Thanks @padre!
20+
21+
### Changed
22+
- detection if cache is enabled in the `$model->all()` method. Thanks @titrxw!
23+
24+
## [0.7.2] - 2019-10-12
25+
### Fixed
26+
- improper caching of non-cachable eagerloaded relationships. Now any query with non-cachable eagerloaded relationships will not be cached in its entirety to prevent stale data. Special thanks to @Hornet-Wing for his help in this.
27+
28+
## [0.7.1] - 2019-10-02
29+
### Fixed
30+
- dependency version constraints.
31+
### Added
32+
- various tests.
33+
34+
## [0.7.0] - 2019-08-28
35+
### Added
36+
- Laravel 6.0 support.
37+
738
## [0.6.3] - 2019-08-27
839
### Fixed
940
- caching of methods that could pass field names as string or array.

README.md

Lines changed: 253 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -1,18 +1,266 @@
11
# Model Caching for Laravel
22
[![Travis](https://img.shields.io/travis/GeneaLabs/laravel-model-caching/master.svg)](https://travis-ci.org/GeneaLabs/laravel-model-caching)
33
[![Scrutinizer](https://img.shields.io/scrutinizer/g/GeneaLabs/laravel-model-caching/master.svg)](https://scrutinizer-ci.com/g/GeneaLabs/laravel-model-caching)
4-
<img src='https://bettercodehub.com/edge/badge/GeneaLabs/laravel-model-caching?branch=master'>
4+
![BCH Compliance](https://bettercodehub.com/edge/badge/GeneaLabs/laravel-model-caching?branch=master)
55
[![Coveralls](https://img.shields.io/coveralls/GeneaLabs/laravel-model-caching/master.svg)](https://coveralls.io/github/GeneaLabs/laravel-model-caching)
66
[![GitHub (pre-)release](https://img.shields.io/github/release/GeneaLabs/laravel-model-caching/all.svg)](https://github.com/GeneaLabs/laravel-model-caching)
77
[![Packagist](https://img.shields.io/packagist/dt/GeneaLabs/laravel-model-caching.svg)](https://packagist.org/packages/genealabs/laravel-model-caching)
88
[![GitHub license](https://img.shields.io/badge/license-MIT-blue.svg)](https://raw.githubusercontent.com/GeneaLabs/laravel-model-caching/master/LICENSE)
99

10-
![pexels-photo-325229](https://user-images.githubusercontent.com/1791050/30768358-0df9d0f2-9fbb-11e7-9f10-ad40b83bbf59.jpg)
11-
12-
Documentation has moved to https://genealabs.com/docs/laravel-model-caching/.
10+
![Model Caching for Laravel masthead image](https://repository-images.githubusercontent.com/103836049/b0d89480-f1b1-11e9-8e13-a7055f008fe6)
1311

1412
## Supporting This Package
15-
This is an MIT-licensed open source project with its ongoing development made possible by the support of the community. If you'd like to support this, and our other packages, please consider [becoming a backer or sponsor on Patreon](https://www.patreon.com/mikebronner).
13+
This is an MIT-licensed open source project with its ongoing development made possible by the support of the community. If you'd like to support this, and our other packages, please consider [becoming a sponsor](https://github.com/sponsors/mikebronner).
14+
15+
## Impetus
16+
I created this package in response to a client project that had complex, nested
17+
forms with many `<select>`'s that resulted in over 700 database queries on one
18+
page. I needed a package that abstracted the caching process out of the model
19+
for me, and one that would let me cache custom queries, as well as cache model
20+
relationships. This package is an attempt to address those requirements.
21+
22+
## Features
23+
- automatic, self-invalidating relationship (only eager-loading) caching.
24+
- automatic, self-invalidating model query caching.
25+
- automatic use of cache tags for cache providers that support them (will
26+
flush entire cache for providers that don't).
27+
28+
## Cache Drivers
29+
This package is best suited for taggable cache drivers:
30+
```diff
31+
+ Redis
32+
+ MemCached
33+
+ APC
34+
+ Array
35+
```
36+
37+
It will not work with non-taggable drivers:
38+
```diff
39+
- Database
40+
- File
41+
- DynamoDB
42+
```
43+
44+
## Requirements
45+
- Laravel 6.0+
46+
```diff
47+
- Please note that prior Laravel versions are not supported and the package
48+
- versions that are compatible with prior versions of Laravel contain bugs.
49+
- Please only use with the versions of Laravel noted above to be compatible.
50+
```
51+
52+
### Possible Conflicting Packages
53+
Any packages that override `newEloquentModel()` from the `Model` class will
54+
likely conflict with this package. Of course, any packages that implement their
55+
own Querybuilder class effectively circumvent this package, rendering them
56+
incompatible.
57+
58+
The following are packages we have identified as incompatible:
59+
- [grimzy/laravel-mysql-spatial](https://github.com/grimzy/laravel-mysql-spatial)
60+
- [fico7489/laravel-pivot](https://github.com/fico7489/laravel-pivot)
61+
- [chelout/laravel-relationship-events](https://github.com/chelout/laravel-relationship-events)
62+
- [spatie/laravel-query-builder](https://github.com/spatie/laravel-query-builder)
63+
- [dwightwatson/rememberable](https://github.com/dwightwatson/rememberable)
64+
65+
### Things That Don't Work Currently
66+
The following items currently do no work with this package:
67+
```diff
68+
- caching of lazy-loaded relationships, see #127. Currently lazy-loaded belongs-to relationships are cached. Caching of other relationships is in the works.
69+
- using select() clauses in Eloquent queries, see #238 (work-around discussed in the issue)
70+
- using transactions. If you are using transactions, you will likely have to manually flush the cache, see [issue #305](https://github.com/GeneaLabs/laravel-model-caching/issues/305).
71+
```
72+
73+
[![installation guide cover](https://user-images.githubusercontent.com/1791050/36356190-fc1982b2-14a2-11e8-85ed-06f8e3b57ae8.png)](https://vimeo.com/256318402)
74+
75+
## Installation
76+
Be sure to not require a specific version of this package when requiring it:
77+
```
78+
composer require genealabs/laravel-model-caching:*
79+
```
80+
81+
## Upgrade Notes
82+
### 0.6.0
83+
The environment and config variables for disabling this package have changed.
84+
- If you have previously published the config file, publish it again, and adjust as necessary:
85+
```sh
86+
php artisan modelCache:publish --config
87+
```
88+
89+
- If you have disabled the package in your .env file, change the entry from `MODEL_CACHE_DISABLED=true` to `MODEL_CACHE_ENABLED=false`.
90+
91+
### 0.5.0
92+
The following implementations have changed (see the respective sections below):
93+
- model-specific cache prefix
94+
95+
## Configuration
96+
### Recommended (Optional) Custom Cache Store
97+
If you would like to use a different cache store than the default one used by
98+
your Laravel application, you may do so by setting the `MODEL_CACHE_STORE`
99+
environment variable in your `.env` file to the name of a cache store configured
100+
in `config/cache.php` (you can define any custom cache store based on your
101+
specific needs there). For example:
102+
```
103+
MODEL_CACHE_STORE=redis2
104+
```
105+
106+
## Usage
107+
For best performance a taggable cache provider is recommended (redis,
108+
memcached). While this is optional, using a non-taggable cache provider will
109+
mean that the entire cache is cleared each time a model is created, saved,
110+
updated, or deleted.
111+
112+
For ease of maintenance, I would recommend adding a `BaseModel` model that
113+
uses `Cachable`, from which all your other models are extended. If you
114+
don't want to do that, simply extend your models directly from `CachedModel`.
115+
116+
Here's an example `BaseModel` class:
117+
118+
```php
119+
<?php namespace App;
120+
121+
use GeneaLabs\LaravelModelCaching\Traits\Cachable;
122+
123+
abstract class BaseModel
124+
{
125+
use Cachable;
126+
//
127+
}
128+
```
129+
130+
### Multiple Database Connections
131+
__Thanks to @dtvmedia for suggestion this feature. This is actually a more robust
132+
solution than cache-prefixes.__
133+
134+
Keeping keys separate for multiple database connections is automatically handled.
135+
This is especially important for multi-tenant applications, and of course any
136+
application using multiple database connections.
137+
138+
### Optional Cache Key Prefix
139+
Thanks to @lucian-dragomir for suggesting this feature! You can use cache key
140+
prefixing to keep cache entries separate for multi-tenant applications. For this
141+
it is recommended to add the Cachable trait to a base model, then set the cache
142+
key prefix config value there.
143+
144+
Here's is an example:
145+
```php
146+
<?php namespace GeneaLabs\LaravelModelCaching\Tests\Fixtures;
147+
148+
use GeneaLabs\LaravelModelCaching\Traits\Cachable;
149+
use Illuminate\Database\Eloquent\Model;
150+
use Illuminate\Database\Eloquent\Relations\BelongsTo;
151+
use Illuminate\Database\Eloquent\Relations\BelongsToMany;
152+
153+
class BaseModel extends Model
154+
{
155+
use Cachable;
156+
157+
protected $cachePrefix = "test-prefix";
158+
}
159+
```
160+
161+
The cache prefix can also be set in the configuration to prefix all cached
162+
models across the board:
163+
```php
164+
'cache-prefix' => 'test-prefix',
165+
```
166+
167+
### Exception: User Model
168+
I would not recommend caching the user model, as it is a special case, since it
169+
extends `Illuminate\Foundation\Auth\User`. Overriding that would break functionality.
170+
Not only that, but it probably isn't a good idea to cache the user model anyway,
171+
since you always want to pull the most up-to-date info on it.
172+
173+
### Experimental: Cache Cool-down In Specific Models
174+
In some instances, you may want to add a cache invalidation cool-down period.
175+
For example you might have a busy site where comments are submitted at a high
176+
rate, and you don't want every comment submission to invalidate the cache. While
177+
I don't necessarily recommend this, you might experiment it's effectiveness.
178+
179+
To use it, it must be enabled in the model (or base model if you want to use it on multiple or all models):
180+
```php
181+
class MyModel extends Model
182+
{
183+
use Cachable;
184+
185+
protected $cacheCooldownSeconds = 300; // 5 minutes
186+
187+
// ...
188+
}
189+
```
190+
191+
After that it can be implemented in queries:
192+
```php
193+
(new Comment)
194+
->withCacheCooldownSeconds(30) // override default cooldown seconds in model
195+
->get();
196+
```
197+
198+
or:
199+
```php
200+
(new Comment)
201+
->withCacheCooldownSeconds() // use default cooldown seconds in model
202+
->get();
203+
```
204+
205+
### Disabling Caching of Queries
206+
There are two methods by which model-caching can be disabled:
207+
1. Use `->disableCache()` in a query-by-query instance.
208+
2. Set `MODEL_CACHE_ENABLED=false` in your `.env` file.
209+
3. If you only need to disable the cache for a block of code, or for non-
210+
eloquent queries, this is probably the better option:
211+
```php
212+
$result = app("model-cache")->runDisabled(function () {
213+
return (new MyModel)->get(); // or any other stuff you need to run with model-caching disabled
214+
});
215+
```
216+
217+
**Recommendation: use option #1 in all your seeder queries to avoid pulling in
218+
cached information when reseeding multiple times.**
219+
You can disable a given query by using `disableCache()` anywhere in the query chain. For example:
220+
```php
221+
$results = $myModel->disableCache()->where('field', $value)->get();
222+
```
223+
224+
### Manual Flushing of Specific Model
225+
You can flush the cache of a specific model using the following artisan command:
226+
```sh
227+
php artisan modelCache:clear --model=App\Model
228+
```
229+
230+
This comes in handy when manually making updates to the database. You could also
231+
trigger this after making updates to the database from sources outside your
232+
Laravel app.
233+
234+
## Summary
235+
**That's all you need to do. All model queries and relationships are now
236+
cached!**
237+
238+
In testing this has optimized performance on some pages up to 900%! Most often
239+
you should see somewhere around 100% performance increase.
240+
241+
## Commitment to Quality
242+
During package development I try as best as possible to embrace good design and development practices, to help ensure that this package is as good as it can
243+
be. My checklist for package development includes:
244+
245+
- ✅ Achieve as close to 100% code coverage as possible using unit tests.
246+
- ✅ Eliminate any issues identified by SensioLabs Insight and Scrutinizer.
247+
- ✅ Be fully PSR1, PSR2, and PSR4 compliant.
248+
- ✅ Include comprehensive documentation in README.md.
249+
- ✅ Provide an up-to-date CHANGELOG.md which adheres to the format outlined
250+
at <https://keepachangelog.com>.
251+
- ✅ Have no PHPMD or PHPCS warnings throughout all code.
252+
253+
## Contributing
254+
Please observe and respect all aspects of the included Code of Conduct <https://github.com/GeneaLabs/laravel-model-caching/blob/master/CODE_OF_CONDUCT.md>.
255+
256+
### Reporting Issues
257+
When reporting issues, please fill out the included template as completely as
258+
possible. Incomplete issues may be ignored or closed if there is not enough
259+
information included to be actionable.
260+
261+
### Submitting Pull Requests
262+
Please review the Contribution Guidelines <https://github.com/GeneaLabs/laravel-model-caching/blob/master/CONTRIBUTING.md>.
263+
Only PRs that meet all criterium will be accepted.
16264

17265
## If you ❤️ open-source software, give the repos you use a ⭐️.
18266
We have included the awesome `symfony/thanks` composer package as a dev

0 commit comments

Comments
 (0)