PHP code example of generoi / sage-cachetags

1. Go to this page and download the library: Download generoi/sage-cachetags 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/ */

    

generoi / sage-cachetags example snippets


use Genero\Sage\CacheTags\Bootstrap;
use Genero\Sage\CacheTags\Actions\Core;
use Genero\Sage\CacheTags\Actions\HttpHeader;
use Genero\Sage\CacheTags\Invalidators\SuperCacheInvalidator;
use Genero\Sage\CacheTags\Stores\WordpressDbStore;

// Bootstrap CacheTags using fluent interface
(new Bootstrap())
    ->store(WordpressDbStore::class)
    ->invalidators([SuperCacheInvalidator::class])
    ->actions([Core::class, HttpHeader::class])
    ->debug(defined('WP_DEBUG') && WP_DEBUG)
    ->httpHeader('Cache-Tag')
    ->bootstrap();

add_filter('cachetags/store-query-string', '__return_false');

add_filter('cachetags/url-ignored-params', fn ($p) => [...$p, 'campaign_id', 'tduid']);

// Change the threshold (default: 50)
add_filter('cachetags/siteground-bulk-purge-threshold', fn () => 100);

// Always flush (never purge individual URLs)
add_filter('cachetags/siteground-bulk-purge-threshold', fn () => 0);

$isProduction = in_array(parse_url(WP_HOME, PHP_URL_HOST), [
    'www.example.com',
]);

return [
    'http-header' => 'Surrogate-Key',
    'store' => CacheTagStore::class,
    'invalidator' => array_filter([
        $isProduction ? FastlySoftCacheInvalidator::class : null,
    ]),
    'action' => [
        Core::class,
        HttpHeader::class,
    ],
];

use Genero\Sage\CacheTags\Actions\Core;
use Genero\Sage\CacheTags\Actions\HttpHeader;
use Genero\Sage\CacheTags\Actions\RestApi;

return [
    'http-header' => 'Cache-Tag',
    'action' => [
        Core::class,
        HttpHeader::class,
        RestApi::class,
    ],
];

public function handle(WP_REST_Request $request): WP_REST_Response
{
    $people = $this->search($request);

    CacheTags::getInstance()?->add([
        'archive:person',
        ...array_map(fn ($p) => "post:{$p->id}", $people),
    ]);

    return rest_ensure_response($people);
}

$cacheTags->add($tags);
$cacheTags->save($request->get_route());
$response->header('Cache-Tag', implode(' ', $tags));

// Tag bespoke REST routes that don't map to a core object.
add_filter('cachetags/rest-tags', function (array $tags, WP_REST_Request $request) {
    return $request->get_route() === '/my-plugin/v1/feed'
        ? [...$tags, 'archive:post']
        : $tags;
}, 10, 2);

// Add or trim the related dependencies tagged for a post response.
// The matched WP_REST_Request is also passed as a third argument.
add_filter('cachetags/rest-related-tags', function (array $tags, WP_Post $post) {
    return $tags;
}, 10, 2);

// Change which query parameters are ignored when building the store URL.
add_filter('cachetags/rest-url-ignored-params', fn (array $params) => [...$params, 'preview']);

// Tag header byte budget before collapsing to coarse tags (default 16384,
// Fastly's Surrogate-Key total). Tune it for a provider with a different limit.
add_filter('cachetags/max-header-bytes', fn () => 8192);

add_filter('cachetags/options', fn (array $options) => [...$options, 'my_option']);

use Genero\Sage\CacheTags\Actions\AutoTag;
use Genero\Sage\CacheTags\Actions\Core;

return [
    'action' => [
        Core::class,
        AutoTag::class,
    ],
];

  add_filter('cachetags/cacheable', fn ($c) => current_user_can('edit_posts') ? $c : true, 5);
  

   // e.g. a product page that prints a WooCommerce Store API nonce for add-to-cart
   add_action('wp_footer', function () {
       if (function_exists('is_product') && is_product()) {
           \Genero\Sage\CacheTags\CacheTags::getInstance()?->add(['nonce']);
       }
   });
   

   add_filter('cachetags/cacheable', fn ($c) => is_page('booking') ? false : $c);
   

namespace App\View\Composers;

use Genero\Sage\CacheTags\Concerns\ComposerCacheTags;
use Genero\Sage\CacheTags\Tags\CoreTags;
use Roots\Acorn\View\Composer;
use Illuminate\View\View;

class ContentSingle extends Composer
{
    use ComposerCacheTags;

    protected static $views = [
        'partials.content-single',
    ];

    /**
     * @return array
     */
    public function with()
    {
        $post = get_post();

        return [
            'post' => $post,
            'date' => $this->date($post),
            'authors' => $this->authors($post),
            'excerpt' => $this->excerpt($post),
            'related' => $this->related($post),
            'categories' => $this->categories($post),
        ];
    }

    public function cacheTags(View $view): array
    {
        return [
            ...CoreTags::posts($view->post),
            ...CoreTags::terms($view->categories),
            ...CoreTags::query($this->related())
        ];
    }
}


namespace App\Blocks;

use Genero\Sage\CacheTags\Tags\CoreTags;
use Genero\Sage\CacheTags\Concerns\BlockCacheTags;

class ArticleList extends Block
{
    use BlockCacheTags;

    public $name = 'Article List';
    public $slug = 'article-list';

    public function cacheTags(): array
    {
        $query = $this->buildQuery();

        return [
            ...CoreTags::archive('post'),
            ...CoreTags::query($query),
        ];
    }
}

// config/cachetags.php
'auto-detect-actions' => false,

// or on the standalone bootstrap
(new Bootstrap)->autoDetectActions(false)->/* … */->bootstrap();

use Genero\Sage\CacheTags\CacheTags;

// Get instance from container
$cacheTags = app(CacheTags::class);

use Genero\Sage\CacheTags\CacheTags;

// Get the singleton instance
$cacheTags = CacheTags::getInstance();

use Genero\Sage\CacheTags\Tag;

Tag::post(5);                    // post:5
Tag::archive('product');         // archive:product
Tag::archive('product')->any();  // archive:product:any  (any product changing)
Tag::term(9)->full();            // term:9:full
Tag::option('blogname');         // option:blogname
Tag::of('my-type', $id);         // an arbitrary custom type

Tag::post(5)->scope('site', 5);                       // site:5:post:5
Tag::post(5)->scope('network', 2)->scope('site', 5);  // network:2:site:5:post:5
Tag::archive('post')->qualify($lang);                 // archive:post:fi

$cacheTags->add(Tag::nonce());                 // a single tag
$cacheTags->add('post:5', Tag::term(9));       // several arguments
$cacheTags->add([
    Tag::archive('product'),
    ...CoreTags::posts($ids),                  // CoreTags returns Tag[]
    'my:custom:tag',                           // plain strings still work
]);

use Genero\Sage\CacheTags\CacheTags;
use Genero\Sage\CacheTags\Tag;

// Tag content (a bare string, or Tag::of('custom-tag') / Tag::of('thing', $id))
app(CacheTags::class)->add(['custom-tag']);

// Clear it whenever you want
\add_action('custom/update', fn() => app(CacheTags::class)->clear(['custom-tag']));

use Genero\Sage\CacheTags\CacheTags;

// Tag content
CacheTags::getInstance()?->add(['custom-tag']);

// Clear it whenever you want
\add_action('custom/update', fn() => CacheTags::getInstance()?->clear(['custom-tag']));