gchaincl / laravel-fragment-caching by gchaincl

Fragment Caching support helper
1,347
34
2
Package Data
Maintainer Username: gchaincl
Maintainer Contact: gustaf@espontanea.io (Gustaf Shin)
Package Create Date: 2014-02-09
Package Last Update: 2016-03-08
Home Page:
Language: PHP
License: MIT
Last Refreshed: 2019-08-13 03:32:57
Package Statistics
Total Downloads: 1,347
Monthly Downloads: 15
Daily Downloads: 0
Total Stars: 34
Total Watchers: 2
Total Forks: 5
Total Open Issues: 2

Not supported No Maintenance Intended

This project is not supported anymore, you can try matryoshka instead.

laravel-fragment-caching

Add a Fragment caching support helper. Blog post

Installation

Run: composer require gchaincl/laravel-fragment-caching:dev-master or

  • add: "require": { "gchaincl/laravel-fragment-caching": "dev-master" },to composer.json
  • run: composer install
  • add: The following to your app/config/app.php
$providers => array(
  ...
 	'Gchaincl\LaravelFragmentCaching\ViewServiceProvider',
)

Usage

In your view:

<ul>
@foreach ($posts as $post)

@cache("post" . $post->id)
    <li> {{ link_to_route('post.show', $post->title, $post->id) }} ({{ $post->user->username }})</li>
@endcache

@endforeach
</ul>

First time we load that view, Framework will run 3 queries:

select * from "posts"
select * from "users" where "users"."id" = '5' limit 1
select * from "users" where "users"."id" = '5' limit 1

Second time, as fragments are already cached, there will be just one query:

select * from "posts"

Conditional caching

In situations where you don't always want to cache a block you can use @cacheif($condition, $cacheId)

{{-- Only use the cache for guests, admins will always get content rendered from the template --}}
@cacheif( Auth::guest(), "post" . $post->id)
    <li> {{ link_to_route('post.show', $post->title, $post->id) }} (@if (Auth::guest()) {{ $post->user->username }} @else {{ $post->user->email }} @endif)</li>
@endcacheif

Tip

To update view rendering on model changes, you should expire your fragments:

// app/model/Post.php

class Post extends Eloquent {

    public static function boot() {
        parent::boot();
        static::updated(function($model) {
            Cache::forget("post" . $model->id);
        });
    }
}