JosephSilber / page-cache

Caches responses as static files on disk for lightning fast page loads.
MIT License
1.21k stars 118 forks source link

Feature Request: Automatically delete cached file with model changes #84

Closed sarfraznawaz2005 closed 3 years ago

sarfraznawaz2005 commented 3 years ago

Any plan to add automatic cache-purge facility when corresponding model changes for a page. For example, we can tell package which routes we want to cache:

// example-package-config
return [
   // routeName => [one ore more model paths]
    'home' => App\Models\Post::class,
    'category.index' => [App\Models\Post::class, App\Models\Category::class],
];

Using something like above, the cached page of homepage will be automatically deleted when there is any change in Post mode. (using model events for example) and will be cached again when page is visited again. Similarly, cached page of category listing page will be deleted when there is change in either model Post or the model Category.

Would also be cool if cache key is made with logged in user id (if logged in) so each user gets his/her own cached content only.

I am not sure if this fits for this package but one thing is for sure that if we have full page cache thing with auto-deletion, laravel community would embrace it fully for obvious speed benefits.

JosephSilber commented 3 years ago

This is quite trivial to add on your own:

use Illuminate\Database\Eloquent\Model;
use Silber\PageCache\Cache;

class Post extends Model
{
    public static function booted()
    {
        static::updated(fn ($post) => $this->flushCache($post));
        static::deleted(fn ($post) => $this->flushCache($post));
    }

    protected static function flushCache(Post $post) 
    {
        $cache = app(Cache::class);

        $cache->forget("posts/{$post->id}");
        $cache->forget("posts");
    }
}

You can tweak that to more precisely fit your setup.

This is too implementation-specific to be worth including in the package directly. The amount of configuration required is about as much as writing the above code yourself.