- Notifications
You must be signed in to change notification settings - Fork231
Eloquent model-caching made easy.
License
mikebronner/laravel-model-caching
Folders and files
Name | Name | Last commit message | Last commit date | |
---|---|---|---|---|
Repository files navigation
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 considerbecoming a sponsor.
We thank the following sponsors for their generosity, please take a moment to check them out:
I created this package in response to a client project that had complex, nestedforms with many<select>
's that resulted in over 700 database queries on onepage. I needed a package that abstracted the caching process out of the modelfor me, and one that would let me cache custom queries, as well as cache modelrelationships. This package is an attempt to address those requirements.
- automatic, self-invalidating relationship (only eager-loading) caching.
- automatic, self-invalidating model query caching.
- automatic use of cache tags for cache providers that support them (willflush entire cache for providers that don't).
This package is best suited for taggable cache drivers:
+ Redis+ MemCached+ APC+ Array
It will not work with non-taggable drivers:
- Database- File- DynamoDB
- PHP 7.3+
- Laravel 8.0+
- Please note that prior Laravel versions are not supported and the package- versions that are compatible with prior versions of Laravel contain bugs.- Please only use with the versions of Laravel noted above to be compatible.
Any packages that overridenewEloquentModel()
from theModel
class willlikely conflict with this package. Of course, any packages that implement theirown Querybuilder class effectively circumvent this package, rendering themincompatible.
The following are packages we have identified as conflicting:
- grimzy/laravel-mysql-spatial
- fico7489/laravel-pivot
- chelout/laravel-relationship-events
- spatie/laravel-query-builder
- dwightwatson/rememberable
- kalnoy/nestedset
- laravel-adjacency-list
The following items currently do no work with this package:
- caching of lazy-loaded relationships, see #127. Currently lazy-loaded belongs-to relationships are cached. Caching of other relationships is in the works.- using select() clauses in Eloquent queries, see #238 (work-around discussed in the issue)- 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).
Be sure to not require a specific version of this package when requiring it:
composer require mikebronner/laravel-model-caching
The following steps need to be figured out by you and implemented in your Lumenapp. Googling for ways to do this provided various approaches to this.
- Register the package to load in Lumen:
$app->register(GeneaLabs\LaravelModelCaching\Providers\Service::class);
- Make sure your Lumen app can load config files.
- Publish this package's config file to the location your app loads configfiles from.
The environment and config variables for disabling this package have changed.
If you have previously published the config file, publish it again, and adjust as necessary:
php artisan modelCache:publish --config
If you have disabled the package in your .env file, change the entry from
MODEL_CACHE_DISABLED=true
toMODEL_CACHE_ENABLED=false
.
The following implementations have changed (see the respective sections below):
- model-specific cache prefix
If you would like to use a different cache store than the default one used byyour Laravel application, you may do so by setting theMODEL_CACHE_STORE
environment variable in your.env
file to the name of a cache store configuredinconfig/cache.php
(you can define any custom cache store based on yourspecific needs there). For example:
MODEL_CACHE_STORE=redis2
For best performance a taggable cache provider is recommended (redis,memcached). While this is optional, using a non-taggable cache provider willmean that the entire cache is cleared each time a model is created, saved,updated, or deleted.
For ease of maintenance, I would recommend adding aBaseModel
model thatusesCachable
, from which all your other models are extended. If youdon't want to do that, simply extend your models directly fromCachedModel
.
Here's an exampleBaseModel
class:
<?phpnamespaceApp;useGeneaLabs\LaravelModelCaching\Traits\Cachable;abstractclass BaseModel{use Cachable;//}
Thanks to @dtvmedia for suggestion this feature. This is actually a more robustsolution than cache-prefixes.
Keeping keys separate for multiple database connections is automatically handled.This is especially important for multi-tenant applications, and of course anyapplication using multiple database connections.
Thanks to @lucian-dragomir for suggesting this feature! You can use cache keyprefixing to keep cache entries separate for multi-tenant applications. For thisit is recommended to add the Cachable trait to a base model, then set the cachekey prefix config value there.
Here's is an example:
<?phpnamespaceGeneaLabs\LaravelModelCaching\Tests\Fixtures;useGeneaLabs\LaravelModelCaching\Traits\Cachable;useIlluminate\Database\Eloquent\Model;useIlluminate\Database\Eloquent\Relations\BelongsTo;useIlluminate\Database\Eloquent\Relations\BelongsToMany;class BaseModelextends Model{use Cachable;protected$cachePrefix ="test-prefix";}
The cache prefix can also be set in the configuration to prefix all cachedmodels across the board:
'cache-prefix' =>'test-prefix',
I would not recommend caching the user model, as it is a special case, since itextendsIlluminate\Foundation\Auth\User
. Overriding that would break functionality.Not only that, but it probably isn't a good idea to cache the user model anyway,since you always want to pull the most up-to-date info on it.
In some instances, you may want to add a cache invalidation cool-down period.For example you might have a busy site where comments are submitted at a highrate, and you don't want every comment submission to invalidate the cache. WhileI don't necessarily recommend this, you might experiment it's effectiveness.
To use it, it must be enabled in the model (or base model if you want to use it on multiple or all models):
class MyModelextends Model{use Cachable;protected$cacheCooldownSeconds =300;// 5 minutes// ...}
After that it can be implemented in queries:
(newComment) ->withCacheCooldownSeconds(30)// override default cooldown seconds in model ->get();
or:
(newComment) ->withCacheCooldownSeconds()// use default cooldown seconds in model ->get();
There are two methods by which model-caching can be disabled:
- Use
->disableCache()
in a query-by-query instance. - Set
MODEL_CACHE_ENABLED=false
in your.env
file. - If you only need to disable the cache for a block of code, or for non-eloquent queries, this is probably the better option:
$result =app("model-cache")->runDisabled(function () {return (newMyModel)->get();// or any other stuff you need to run with model-caching disabled});
Recommendation: use option #1 in all your seeder queries to avoid pulling incached information when reseeding multiple times.You can disable a given query by usingdisableCache()
anywhere in the query chain. For example:
$results =$myModel->disableCache()->where('field',$value)->get();
You can flush the cache of a specific model using the following artisan command:
php artisan modelCache:clear --model=App\Model
This comes in handy when manually making updates to the database. You could alsotrigger this after making updates to the database from sources outside yourLaravel app.
That's all you need to do. All model queries and relationships are nowcached!
In testing this has optimized performance on some pages up to 900%! Most oftenyou should see somewhere around 100% performance increase.
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 canbe. My checklist for package development includes:
- ✅ Achieve as close to 100% code coverage as possible using unit tests.
- ✅ Eliminate any issues identified by SensioLabs Insight and Scrutinizer.
- ✅ Be fully PSR1, PSR2, and PSR4 compliant.
- ✅ Include comprehensive documentation in README.md.
- ✅ Provide an up-to-date CHANGELOG.md which adheres to the format outlinedathttps://keepachangelog.com.
- ✅ Have no PHPMD or PHPCS warnings throughout all code.
Please observe and respect all aspects of the included Code of Conducthttps://github.com/GeneaLabs/laravel-model-caching/blob/master/CODE_OF_CONDUCT.md.
When reporting issues, please fill out the included template as completely aspossible. Incomplete issues may be ignored or closed if there is not enoughinformation included to be actionable.
Please review the Contribution Guidelineshttps://github.com/GeneaLabs/laravel-model-caching/blob/master/CONTRIBUTING.md.Only PRs that meet all criterium will be accepted.
We have included the awesomesymfony/thanks
composer package as a devdependency. Let your OS package maintainers know you appreciate them by starringthe packages you use. Simply run composer thanks after installing this package.(And not to worry, since it's a dev-dependency it won't be installed in yourlive environment.)
About
Eloquent model-caching made easy.
Topics
Resources
License
Code of conduct
Uh oh!
There was an error while loading.Please reload this page.
Stars
Watchers
Forks
Packages0
Uh oh!
There was an error while loading.Please reload this page.