Description
Firstly, thank you very much for this great package!
Is your feature request related to a problem? Please describe.
While using this package in my project I have found that some of my models which do not have the Cacheable
trait, for example the User
model, get cached as part of any eager loads with models that have the Cacheable
trait.
For example:
Team: has Cacheable
User: doesn't have Cacheable
App\Team::with('users')->find(1);
The above will cache the result which will contain the team details as well as all user details. The problem arises when a user changes their details. When the above is rerun the result will not reflect the changes as the cache was not invalidated.
I believe this is because the User
model doesn't have the Cacheable
trait in the first place, it will also not have the ModelCaching
trait which adds the necessary listeners to invalidate the cache with the model's tag.
Describe the solution you'd like
I believe what is required is a generic trait that can be applied to all the models (which do not have the Cacheable
trait) within the application so that all changes will cause a cache invalidation for that tag.
I had a quick go at how that trait might look just to demonstrate the principle. There are still a few kinks I still need to work out, such as just using the Caching
trait doesn't quite work.
<?php
namespace App\Traits;
use Illuminate\Support\Facades\Artisan;
use GeneaLabs\LaravelModelCaching\Traits\Caching;
trait InvalidateCacheable
{
use Caching;
protected static function bootInvalidateCacheable()
{
static::created(function ($instance) {
$instance->clearModelCache();
});
static::deleted(function ($instance) {
$instance->clearModelCache();
});
static::saved(function ($instance) {
$instance->clearModelCache();
});
}
protected function clearModelCache()
{
$this->flushCache();
// OR
// Artisan::call(
// 'modelCache:clear',
// [
// '--model' => get_class($this),
// ]
// );
}
}
Describe alternatives you've considered
An alternative would be to disableCache
for all queries that reference a model that does not have the Cacheable trait. This is a perfectly feasible work around, however, it does rely on always remembering to do this which I don't believe is possible, especially in a team of developers.
I am happy to work on this if it makes sense and I haven't missed something that already exists in the package.