Stash view is a composer package for Laravel which caches views using Russian Doll Caching methodology.

Overview

Stash View

Stash view is a composer package for Laravel which caches views using Russian Doll Caching methodology.

What is Russian Doll Caching ? It is really famous caching stratergy to cache your views into small chunks. It is quite famous in Rails community. If you are interested to know more checkout this link.

In a nutshell, It caches your views into chunks. This article will give you more clear idea.

Russian Doll Caching PNG

Now enough about idea let's talk about how to use it

You can also checkout example code from here

Want video explaination of internals? check this youtube link.

Installation

Step 1: Composer

Firstly require this package using following command.

composer require enlight/stash-view

Step 2: Service Provider (Optional)

This package supports auto discovery but if you are using Laravel 5.4 or below you need to add ServiceProvider into providers array.

For your Laravel app, open config/app.php and, within the providers array, append:

Enlight\StashView\Providers\StashViewServiceProvider::class

This will bootstrap the package into Laravel.

Step 3: Cache Driver

For this package to function properly, you must use a Laravel cache driver that supports tagging (like Cache::tags('foo')). Drivers such as Memcached and Redis support this feature.

Check your .env file, and ensure that your CACHE_DRIVER choice accomodates this requirement:

CACHE_DRIVER=redis

NOTE: If your application is set to local environment then by default this package will use array caching driver to speed up development process so that you don't need to clear cache again and again while developing.

Have a look at Laravel's cache configuration documentation, if you need any help.

Usage

The Basics

With the package now installed, you may use the provided @cache Blade directive anywhere in your views, like so:

@cache('my-cache-key')
    <div>
        <h1>Hello Worldh1>
    div>
@endcache

By surrounding this block of HTML with the @cache and @endcache directives, we're asking the package to cache the given HTML. Now this example is trivial, however, you can imagine a more complex view that includes various nested caches, as well as lazy-loaded relationship calls that trigger additional database queries. After the initial page load that caches the HTML fragment, each subsequent refresh will instead pull from the cache. As such, those additional database queries will never be executed. Really cool side effect of this package is it reduces you sql queries and solves n+1 problem out of the box.

Please keep in mind that, in production, this will cache the HTML fragment "forever". For local development, on the other hand, we are using array cache driver which stores the cache in memory and flush out when work done. That way, you may update your views and templates however you wish, without needing to worry about clearing the cache manually.

Now because your production server will cache the fragments forever, you'll want to add a step to your deployment process that clears the relevant cache.

Cache::tags('views')->flush();

Caching Models

While you're free to hard-code any string for the cache key, the true power of Russian-Doll caching comes into play when we use a timestamp-based approach.

Consider the following fragment:

{{ $post->body }}
@endcache ">
@cache($post)
    <article>
        <h2>{{ $post->title }}>h2>
        <p>Written By: {{ $post->author->username }}p>

        <div class="body">{{ $post->body }}div>
    article>
@endcache

In this example, we're passing the $post object, itself, to the @cache directive - rather than a string. The package will then look for a getCacheKey() method on the model. We've already done that work for you; just have your Eloquent model use the Enlight\StashView\Traits\Cacheable trait, like so:

use Enlight\StashView\Traits\Cacheable;

class Post extends Eloquent
{
    use Cacheable;
}

Alternatively, you may use this trait on a parent class that each of your Eloquent models extend.

That should do it! Now, the cache key for this fragment will include the object's Primary Key ie id in most cases and updated_at timestamp: App\Post/1-98765432101.

The key is that, because we factor the updated_at timestamp into the cache key, whenever you update the given post, the cache key will change. This will then, in effect, bust the cache!

Touching

In order for this technique to work properly, it's vital that we have some mechanism to alert parent relationships (and subsequently bust parent caches) each time a model is updated. Here's a basic workflow:

  1. Model is updated in the database.
  2. Its updated_at timestamp is refreshed, triggering a new cache key for the instance.
  3. The model "touches" (or pings) its parent.
  4. The parent's updated_at timestamp, too, is updated, which busts its associated cache.
  5. Only the affected fragments re-render. All other cached items remain untouched.

Luckily, Laravel offers this "touch" functionality out of the box. Consider a Note object that needs to alert its parent Card relationship each time an update occurs.



namespace App;

use Enlight\StashView\Traits\Cacheable;
use Illuminate\Database\Eloquent\Model;

class Note extends Model
{
    use Cacheable;

    protected $touches = ['card'];

    public function card()
    {
        return $this->belongsTo(Card::class);
    }
}

Notice the $touches = ['card'] portion. This instructs Laravel to ping the card relationship's timestamps each time the note is updated.

Now, everything is in place. You might render your view, like so:

resources/views/cards/_card.blade.php

{{ $card->title }}

    @foreach ($card->notes as $note) @include ('cards/_note') @endforeach
@endcache ">
@cache($card)
    <article class="Card">
        <h2>{{ $card->title }}h2>

        <ul>
            @foreach ($card->notes as $note)
                @include ('cards/_note')
            @endforeach
        ul>
    article>
@endcache

resources/views/cards/_note.blade.php

@cache($note)
    <li>{{ $note->body }}li>
@endcache

Notice the Russian-Doll style cascading for our caches; that's the key. If any note is updated, its individual cache will clear - long with its parent - but any siblings will remain untouched.

Caching Collections

Its not yet supported but this is already in todo list. Will appreciate any good PR for this. :)

FAQ

1. Is there any way to override the cache key for a model instance?

Yes. Let's say you have:

@cache($post)
    <div>view herediv>
@endcache

Behind the scenes, we'll look for a getCacheKey method on the model. Now, as mentioned above, you can use the Enlight\StashView\Traits\Cacheable trait to instantly import this functionality. Alternatively, you may pass your own cache key to the @cache directive, like this:

@cache('post-pagination')
    <div>view herediv>
@endcache

This instructs the package to use post-pagination for the cache instead. This can be useful for pagination and other related tasks.

That's it. Thank You :)

Happy Coding.

You might also like...
Jetstrap is a lightweight laravel 8 package that focuses on the VIEW side of Jetstream / Breeze package installed in your Laravel application

A Laravel 8 package to easily switch TailwindCSS resources generated by Laravel Jetstream and Breeze to Bootstrap 4.

A package to easily make use of Iconic icons in your Laravel Blade views.
A package to easily make use of Iconic icons in your Laravel Blade views.

Blade Iconic A package to easily make use of Iconic icons in your Laravel Blade views. For a full list of available icons see the SVG directory. Iconi

A package to easily make use of Simple Icons in your Laravel Blade views.
A package to easily make use of Simple Icons in your Laravel Blade views.

Blade Simple Icons A package to easily make use of Simple Icons in your Laravel Blade views. For a full list of available icons see the SVG directory.

A package to easily make use of SVG icons in your Laravel Blade views.
A package to easily make use of SVG icons in your Laravel Blade views.

Blade Icons A package to easily make use of SVG icons in your Laravel Blade views. Originally "Blade SVG" by Adam Wathan. Turn... !-- camera.svg --

A package to easily make use of Iconsax in your Laravel Blade views.
A package to easily make use of Iconsax in your Laravel Blade views.

Blade Iconsax A package to easily make use of Iconsax in your Laravel Blade views. This package contains 1.000 icons in 6 diferent styles, a total of

πŸ‘€ Manage your views in Laravel projects through artisan
πŸ‘€ Manage your views in Laravel projects through artisan

Artisan View This package adds a handful of view-related commands to Artisan in your Laravel project. Generate blade files that extend other views, sc

πŸ§‘β€πŸ”¬ The missing assertions for your views in your Laravel applications.
πŸ§‘β€πŸ”¬ The missing assertions for your views in your Laravel applications.

Laravel View Assertions The missing assertions for your views in your Laravel applications. Installation You'll have to follow a couple of simple step

Cagilo - a set of simple components for use in your views Laravel Blade.

Cagilo - a set of simple components for use in your views Laravel Blade. Official Documentation Documentation for Cagilo can be found on its we

Take a look into your Laravel views
Take a look into your Laravel views

Xray - Take a look into your Laravel views When your Laravel project grows, so do the Laravel views. Sometimes it might be hard to figure out, which p

Comments
  • Bump league/flysystem from 1.1.3 to 1.1.4

    Bump league/flysystem from 1.1.3 to 1.1.4

    Bumps league/flysystem from 1.1.3 to 1.1.4.

    Commits

    Dependabot compatibility score

    Dependabot will resolve any conflicts with this PR as long as you don't alter it yourself. You can also trigger a rebase manually by commenting @dependabot rebase.


    Dependabot commands and options

    You can trigger Dependabot actions by commenting on this PR:

    • @dependabot rebase will rebase this PR
    • @dependabot recreate will recreate this PR, overwriting any edits that have been made to it
    • @dependabot merge will merge this PR after your CI passes on it
    • @dependabot squash and merge will squash and merge this PR after your CI passes on it
    • @dependabot cancel merge will cancel a previously requested merge and block automerging
    • @dependabot reopen will reopen this PR if it is closed
    • @dependabot close will close this PR and stop Dependabot recreating it. You can achieve the same result by closing it manually
    • @dependabot ignore this major version will close this PR and stop Dependabot creating any more for this major version (unless you reopen the PR or upgrade to it yourself)
    • @dependabot ignore this minor version will close this PR and stop Dependabot creating any more for this minor version (unless you reopen the PR or upgrade to it yourself)
    • @dependabot ignore this dependency will close this PR and stop Dependabot creating any more for this dependency (unless you reopen the PR or upgrade to it yourself)
    • @dependabot use these labels will set the current labels as the default for future PRs for this repo and language
    • @dependabot use these reviewers will set the current reviewers as the default for future PRs for this repo and language
    • @dependabot use these assignees will set the current assignees as the default for future PRs for this repo and language
    • @dependabot use this milestone will set the current milestone as the default for future PRs for this repo and language

    You can disable automated security fix PRs for this repo from the Security Alerts page.

    dependencies 
    opened by dependabot[bot] 1
  • Bump laravel/framework from 7.29.3 to 7.30.3

    Bump laravel/framework from 7.29.3 to 7.30.3

    Bumps laravel/framework from 7.29.3 to 7.30.3.

    Release notes

    Sourced from laravel/framework's releases.

    v7.30.3

    v7.30.3 (2021-01-15)

    v7.30.2

    v7.30.2 (2021-01-13)

    Added

    • Added strings to DetectsLostConnections (#35752)

    Fixed

    • Fixed error from missing null check on PHP 8 (#35797)
    • Limit expected bindings (#35865)

    Changed

    • Retry connection if DNS lookup fails (#35790)

    v7.30.1

    v7.30.1 (2020-12-22)

    Fixed

    • Backport for fix issue with polymorphic morphMaps with literal 0 (#35487)
    • Fixed mime validation for jpeg files (#35518)
    • Fixed Illuminate\Validation\Concerns\ValidatesAttributes::validateJson() for PHP8 (#35646)
    • Catch DecryptException with invalid X-XSRF-TOKEN in Illuminate\Foundation\Http\Middleware\VerifyCsrfToken (#35671)

    v7.30.0

    v7.30.0 (2020-12-01)

    Fixed

    • Turn the eloquent collection into a base collection if mapWithKeys loses models (#35129)
    • Fixed pivot restoration (#35218)
    • Fixing BroadcastException message in PusherBroadcaster@broadcast (#35290)
    • Fixed generic DetectsLostConnection string (#35323)
    • Backport Redis context option (#35370)
    • Fixed validating image/jpeg images after Symfony/Mime update (#35419)

    Changed

    • Updated aws/aws-sdk-php suggest to ^3.155 (#35267)
    Commits

    Dependabot compatibility score

    Dependabot will resolve any conflicts with this PR as long as you don't alter it yourself. You can also trigger a rebase manually by commenting @dependabot rebase.


    Dependabot commands and options

    You can trigger Dependabot actions by commenting on this PR:

    • @dependabot rebase will rebase this PR
    • @dependabot recreate will recreate this PR, overwriting any edits that have been made to it
    • @dependabot merge will merge this PR after your CI passes on it
    • @dependabot squash and merge will squash and merge this PR after your CI passes on it
    • @dependabot cancel merge will cancel a previously requested merge and block automerging
    • @dependabot reopen will reopen this PR if it is closed
    • @dependabot close will close this PR and stop Dependabot recreating it. You can achieve the same result by closing it manually
    • @dependabot ignore this major version will close this PR and stop Dependabot creating any more for this major version (unless you reopen the PR or upgrade to it yourself)
    • @dependabot ignore this minor version will close this PR and stop Dependabot creating any more for this minor version (unless you reopen the PR or upgrade to it yourself)
    • @dependabot ignore this dependency will close this PR and stop Dependabot creating any more for this dependency (unless you reopen the PR or upgrade to it yourself)
    • @dependabot use these labels will set the current labels as the default for future PRs for this repo and language
    • @dependabot use these reviewers will set the current reviewers as the default for future PRs for this repo and language
    • @dependabot use these assignees will set the current assignees as the default for future PRs for this repo and language
    • @dependabot use this milestone will set the current milestone as the default for future PRs for this repo and language

    You can disable automated security fix PRs for this repo from the Security Alerts page.

    dependencies 
    opened by dependabot[bot] 1
  • Bump laravel/framework from 7.29.3 to 7.30.4

    Bump laravel/framework from 7.29.3 to 7.30.4

    Bumps laravel/framework from 7.29.3 to 7.30.4.

    Release notes

    Sourced from laravel/framework's releases.

    v7.30.4

    Fixed

    • Fixed empty html mail (#35941)
    • Fixed type error in Illuminate\Http\Concerns\InteractsWithContentTypes::isJson() (#35956)
    • Limit expected bindings (#35972, 006873d)

    v7.30.3

    v7.30.3 (2021-01-15)

    v7.30.2

    v7.30.2 (2021-01-13)

    Added

    • Added strings to DetectsLostConnections (#35752)

    Fixed

    • Fixed error from missing null check on PHP 8 (#35797)
    • Limit expected bindings (#35865)

    Changed

    • Retry connection if DNS lookup fails (#35790)

    v7.30.1

    v7.30.1 (2020-12-22)

    Fixed

    • Backport for fix issue with polymorphic morphMaps with literal 0 (#35487)
    • Fixed mime validation for jpeg files (#35518)
    • Fixed Illuminate\Validation\Concerns\ValidatesAttributes::validateJson() for PHP8 (#35646)
    • Catch DecryptException with invalid X-XSRF-TOKEN in Illuminate\Foundation\Http\Middleware\VerifyCsrfToken (#35671)

    v7.30.0

    v7.30.0 (2020-12-01)

    Fixed

    • Turn the eloquent collection into a base collection if mapWithKeys loses models (#35129)
    • Fixed pivot restoration (#35218)
    • Fixing BroadcastException message in PusherBroadcaster@broadcast (#35290)
    • Fixed generic DetectsLostConnection string (#35323)
    • Backport Redis context option (#35370)
    • Fixed validating image/jpeg images after Symfony/Mime update (#35419)

    Changed

    • Updated aws/aws-sdk-php suggest to ^3.155 (#35267)
    Commits

    Dependabot compatibility score

    Dependabot will resolve any conflicts with this PR as long as you don't alter it yourself. You can also trigger a rebase manually by commenting @dependabot rebase.


    Dependabot commands and options

    You can trigger Dependabot actions by commenting on this PR:

    • @dependabot rebase will rebase this PR
    • @dependabot recreate will recreate this PR, overwriting any edits that have been made to it
    • @dependabot merge will merge this PR after your CI passes on it
    • @dependabot squash and merge will squash and merge this PR after your CI passes on it
    • @dependabot cancel merge will cancel a previously requested merge and block automerging
    • @dependabot reopen will reopen this PR if it is closed
    • @dependabot close will close this PR and stop Dependabot recreating it. You can achieve the same result by closing it manually
    • @dependabot ignore this major version will close this PR and stop Dependabot creating any more for this major version (unless you reopen the PR or upgrade to it yourself)
    • @dependabot ignore this minor version will close this PR and stop Dependabot creating any more for this minor version (unless you reopen the PR or upgrade to it yourself)
    • @dependabot ignore this dependency will close this PR and stop Dependabot creating any more for this dependency (unless you reopen the PR or upgrade to it yourself)
    • @dependabot use these labels will set the current labels as the default for future PRs for this repo and language
    • @dependabot use these reviewers will set the current reviewers as the default for future PRs for this repo and language
    • @dependabot use these assignees will set the current assignees as the default for future PRs for this repo and language
    • @dependabot use this milestone will set the current milestone as the default for future PRs for this repo and language

    You can disable automated security fix PRs for this repo from the Security Alerts page.

    dependencies 
    opened by dependabot[bot] 0
  • Bump symfony/http-kernel from 5.1.3 to 5.1.5

    Bump symfony/http-kernel from 5.1.3 to 5.1.5

    Bumps symfony/http-kernel from 5.1.3 to 5.1.5.

    Release notes

    Sourced from symfony/http-kernel's releases.

    v5.1.5

    Changelog (https://github.com/symfony/http-kernel/compare/v5.1.4...v5.1.5)

    • no changes

    v5.1.4

    Changelog (https://github.com/symfony/http-kernel/compare/v5.1.3...v5.1.4)

    • bug #37841 Backport handler lock when using VAR_DUMPER_FORMAT (ogizanagi)
    Commits
    • 3e32676 Update VERSION for 5.1.5
    • f855601 Merge branch '4.4' into 5.1
    • cdf1e9b security #cve-2020-15094 Remove headers with internal meaning from HttpClient...
    • 8e8d0ed Remove headers with internal meaning from HttpClient responses
    • 05293dd Bump Symfony version to 5.1.5
    • f829c24 Update VERSION for 5.1.4
    • a5ed890 Bump Symfony version to 4.4.13
    • f93f6b3 Update VERSION for 4.4.12
    • 794f3d4 Merge branch '4.4' into 5.1
    • 98fb210 minor #37831 stop using deprecated PHPUnit APIs (xabbuh)
    • Additional commits viewable in compare view

    Dependabot compatibility score

    Dependabot will resolve any conflicts with this PR as long as you don't alter it yourself. You can also trigger a rebase manually by commenting @dependabot rebase.


    Dependabot commands and options

    You can trigger Dependabot actions by commenting on this PR:

    • @dependabot rebase will rebase this PR
    • @dependabot recreate will recreate this PR, overwriting any edits that have been made to it
    • @dependabot merge will merge this PR after your CI passes on it
    • @dependabot squash and merge will squash and merge this PR after your CI passes on it
    • @dependabot cancel merge will cancel a previously requested merge and block automerging
    • @dependabot reopen will reopen this PR if it is closed
    • @dependabot close will close this PR and stop Dependabot recreating it. You can achieve the same result by closing it manually
    • @dependabot ignore this major version will close this PR and stop Dependabot creating any more for this major version (unless you reopen the PR or upgrade to it yourself)
    • @dependabot ignore this minor version will close this PR and stop Dependabot creating any more for this minor version (unless you reopen the PR or upgrade to it yourself)
    • @dependabot ignore this dependency will close this PR and stop Dependabot creating any more for this dependency (unless you reopen the PR or upgrade to it yourself)
    • @dependabot use these labels will set the current labels as the default for future PRs for this repo and language
    • @dependabot use these reviewers will set the current reviewers as the default for future PRs for this repo and language
    • @dependabot use these assignees will set the current assignees as the default for future PRs for this repo and language
    • @dependabot use this milestone will set the current milestone as the default for future PRs for this repo and language

    You can disable automated security fix PRs for this repo from the Security Alerts page.

    dependencies 
    opened by dependabot[bot] 0
Releases(0.0.4)
Owner
Bhushan Gaikwad
Bhushan Gaikwad
Laravel Composable View Composers Package - Compose View Composers from Component Composers

Laravel Virtuoso Laravel Composable View Composers Package Increase flexibility and reduce code duplication by easily composing complex View Composers

Yitzchok Willroth 68 Dec 29, 2021
GitScrum is a Project Management Tool, developed to help entrepreneurs, freelancers, managers, and teams Skyrocket their Productivity with the Agile methodology and Gamification.

What is GitScrum? GitScrum is a Project Management Tool, developed to help entrepreneurs, freelancers, managers, and teams Skyrocket their Productivit

GitScrum 2.8k Dec 29, 2022
Caches responses as static files on disk for lightning fast page loads.

Laravel Page Cache This package allows you to easily cache responses as static files on disk for lightning fast page loads. Introduction Installation

Joseph Silber 1k Dec 16, 2022
Invalidate caches and achieve high hitrate with readable and maintainable annotations

Purgatory Purgatory is an extension which makes it possible for Symfony applications to handle enormous load using minimal infrastructure. Infrastruct

null 45 Nov 30, 2022
A package that adds view-composer like feature to Inertia.js Laravel adapter

Kinetic A package that adds view-composer like feature to Inertia.js Laravel adapter. Use to be able to share props based on the Inertia component nam

Marvin Quezon 76 Dec 12, 2022
Composer package which adds support for HTML5 elements using Laravels Form interface (e.g. Form::date())

Laravel HTML 5 Inputs Composer package which adds support for HTML5 elements by extending Laravel's Form interface (e.g. Form::date()) Adds support fo

Small Dog Studios 11 Oct 13, 2020
Is an Extension of Laravel View Class which compiles String Template on the fly. It automatically detects changes on your string template and recompiles it if needed.

Laravel-fly-view Is an Extension of Laravel View Class which compiles String Template on the fly. It automatically detects changes on your string temp

John Turingan 16 Jul 17, 2022
Create Laravel views (blade template) using 'php artisan' command-line interface

About LaraBit Have you ever wonder to create Laravel views (Blade Templates) using the same type of artisan commands that you usually use to create ne

Ragib MRB 5 Oct 15, 2021
A package that uses blade templates to control how markdown is converted to HTML inside Laravel, as well as providing support for markdown files to Laravel views.

Install Install via composer. $ composer require olliecodes/laravel-etched-blade Once installed you'll want to publish the config. $ php artisan vendo

Ollie Codes 19 Jul 5, 2021
Easily add a full Laravel blog (with built in admin panel and public views) to your laravel project with this simple package.

Webdevetc BlogEtc - Complete Laravel Blog Package Quickly add a blog with admin panel to your existing Laravel project. It has everything included (ro

WebDevEtc. 227 Dec 25, 2022