PHP code example of daun / statamic-cache-directives

1. Go to this page and download the library: Download daun/statamic-cache-directives library. Choose the download type require.

2. Extract the ZIP file and open the index.php.

3. Add this code to the index.php.
    
        
<?php
require_once('vendor/autoload.php');

/* Start to develop here. Best regards https://php-download.com/ */

    

daun / statamic-cache-directives example snippets


use Daun\StatamicCacheDirectives\CacheDirectiveReplacer;

class AppServiceProvider extends ServiceProvider
{
    public function boot(): void
    {
        CacheDirectiveReplacer::variable('editor', fn () => auth()->user()?->hasRole('editor') ?? false);
        CacheDirectiveReplacer::variable('member', fn () => auth()->user()?->isInGroup('members') ?? false);
    }
}

use Daun\StatamicCacheDirectives\CacheDirectiveReplacer;

class AppServiceProvider extends ServiceProvider
{
    public function boot(): void
    {
        CacheDirectiveReplacer::variables([
            'in_uk' => fn () => app(GeoIp::class)->countryCode(request()->ip()) === 'UK',
            'has_cart' => fn () => (bool) session('cart.items'),
        ]);
    }
}

// When rendering untrusted values into a page, neutralize directive markers.
$safe = str_replace('<!--[', '<!--&#91;', $userContent);
html
<!--[if logged_in]-->
  <a href="/account">Account</a>
<!--[endif]-->

<!--[if logged_out]>
  <a href="/login">Log in</a>
<![endif]-->
html
<a href="/account" data-cache="<!--[echo cache_status]-->">
  <!--[echo account_label]-->
</a>

<!--[echo cache_status]>Unknown<![endecho]-->
html
<nav>
  <!--[if logged_in]-->
    <a href="/account">Account</a>
    <form method="POST" action="/logout">
      <button type="submit">Log out</button>
    </form>
  <!--[endif]-->

  <!--[if logged_out]-->
    <a href="/login">Log in</a>
    <a href="/register" class="button">Create account</a>
  <!--[endif]-->
</nav>