laracasts / matryoshka

Russian Doll Caching in Laravel

Home Page:https://laracasts.com/series/russian-doll-caching-in-laravel

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

Different cacheKey for the same model

hugo-lovighi opened this issue · comments

commented

In your package, i can see that we have a single cached view for a model ?!

It could be great to pass different "versions of card model key" and generate several keys like :

App\Card/preview-1-1457710078
App\Card/full-1-1457710078

used in blade: @cache($card, ['preview']))
$item->getCacheKey('preview-version')

used in blade: @cache($card, ['full']))
$item->getCacheKey('full-version')

I'm working on your code to use it in my project, because in my case it's impossible to use different design for a same model for the moment.

@kesm0 any update on this?

commented

Not really, I add some "tricky" code lines to make it work.
I modified 2 files.

BladeDirective.php : (line 72 to 76)

// Otherwise we'll try to use the item to calculate
// the cache key, itself.
if (is_object($item) && method_exists($item, 'getCacheKey')) {

        $version = $key[0];   // Sets multiple cache versions

        return $item->getCacheKey($version);
}

Cacheable.php : (line 13)

/**
 * Calculate a unique cache key for the model instance.
 */
public function getCacheKey($version)
{
    return sprintf("%s-%s/%s-%s",
        $version, // Get the required cache version
        get_class($this),
        $this->getKey(),
        $this->updated_at->timestamp
    );
}

And I use it in blade like this :

views/posts/home.php :

@foreach ($posts as $post)
    @cache($post, ['posts.home'])
        <h2>{{ $post->title }} - {{ $post->created_at }} - {{ $post->author->name }}</h2>
       <p>{{ $post->content }}</p>
    @endcache
@endforeach

views/posts/menu.php :

@foreach ($posts as $post)
    @cache($post, ['posts.menu'])
        <div>{{ $post->title }} - {{ str_limit($post->content, 30) }}</div>
    @endcache
@endforeach

When you update your post, every views are refresh !