PHP code example of pattonwebz / wp-stale-cache

1. Go to this page and download the library: Download pattonwebz/wp-stale-cache 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/ */

    

pattonwebz / wp-stale-cache example snippets


use Pattonwebz\WpStaleCache\CronHandler;

add_action('init', function () {
    CronHandler::register();
});

use Pattonwebz\WpStaleCache\StaleCache;

$cache = new StaleCache(); // default prefix: _wpsc_

$posts = $cache->get(
    'recent_posts',
    [MyDataService::class, 'fetchRecentPosts'],
    3600,       // Fresh for 1 hour
    300         // Serve stale for 5 extra minutes while refreshing in background
);

// Delete a single entry (e.g. when a post is saved)
add_action('save_post', function () use ($cache) {
    $cache->forget('recent_posts');
});

// Flush every option this instance manages
$cache->flush();

// Flush options matching a custom prefix
$cache->flush('_wpsc_products_');

$state = $cache->getState('recent_posts');
// Returns: 'fresh' | 'stale' | 'expired' | 'missing'

$cache = new StaleCache( '_mysite_cache_' );

use Pattonwebz\WpStaleCache\TransientStaleCache;

$cache = new TransientStaleCache( '_wpsc_' ); // same constructor, same API

$posts = $cache->get(
    'recent_posts',
    [MyDataService::class, 'fetchRecentPosts'],
    3600,
    300,
);

$cache->forget('recent_posts');

use PattonWebz\Psr3Logger\Logger;
use Pattonwebz\WpStaleCache\StaleCache;

$logger = new Logger();
$cache  = new StaleCache( '_myplugin_' );
$cache->set_logger( $logger );

use PattonWebz\Psr3Logger\Logger;
use Pattonwebz\WpStaleCache\CronHandler;

CronHandler::set_logger( new Logger() );

use Pattonwebz\WpStaleCache\CronHandler;
use Pattonwebz\WpStaleCache\StaleCache;

// Register once — e.g. in the plugin bootstrap or functions.php.
add_action( 'init', function () {
    CronHandler::register();
} );

$cache = new StaleCache(); // default prefix: _wpsc_

// Fresh for 1 hour; serve stale for 5 minutes while WP-Cron refreshes.
$recent_posts = $cache->get(
    'recent_posts',
    [ MyDataService::class, 'get_recent_posts' ], // array callable — serialisable for cron
    3600, // ttl: fresh window in seconds
    300   // stale_offset: extra seconds to serve stale before forcing a sync regeneration
);

use Pattonwebz\WpStaleCache\StaleCache;

// All keys are stored as _myplugin_{key} and _myplugin_{key}_meta in wp_options.
$cache = new StaleCache( '_myplugin_' );

$menu_items = $cache->get(
    'primary_nav',
    [ MyMenuHelper::class, 'build_primary_nav' ],
    1800, // fresh for 30 minutes
    120   // serve stale for 2 minutes
);

$products_cache = new StaleCache( '_myshop_products_' );
$settings_cache = new StaleCache( '_myshop_settings_' );

use Pattonwebz\WpStaleCache\StaleCache;

$cache = new StaleCache( '_myplugin_' );

// Invalidate a single entry whenever the underlying data changes.
// Both the value option and its _meta companion are deleted.
add_action( 'save_post', function ( $post_id ) use ( $cache ) {
    if ( wp_is_post_revision( $post_id ) ) {
        return;
    }
    $cache->forget( 'recent_posts' );
} );

// Flush every option managed by this cache instance.
// Useful during plugin deactivation or after a bulk import.
add_action( 'my_plugin_data_import_complete', function () use ( $cache ) {
    $cache->flush(); // flushes all _myplugin_* options
} );

// Flush a different prefix without a separate instance.
// Handy when you need to clear one logical group from a shared context.
add_action( 'switch_theme', function () {
    $cache = new StaleCache( '_mytheme_' );
    $cache->flush( '_mytheme_nav_' ); // clears only nav-related keys
} );

$state = $cache->get_state( 'recent_posts' ); // 'fresh' | 'stale' | 'expired' | 'missing'

if ( 'fresh' !== $state ) {
    $cache->forget( 'recent_posts' );
}

use Pattonwebz\WpStaleCache\TransientStaleCache;

$cache = new TransientStaleCache( '_myplugin_' );

// Identical call signature to StaleCache::get().
$feed_items = $cache->get(
    'rss_feed',
    [ MyFeedReader::class, 'fetch_items' ],
    900, // fresh for 15 minutes
    180  // serve stale for 3 more minutes
);

// Invalidate a single key.
$cache->forget( 'rss_feed' );

// Note: TransientStaleCache does not implement flush().
// WordPress provides no native API to query transients by prefix,
// so bulk deletion is deferred to a future version.


// MyPlugin/WeatherService.php
namespace MyPlugin;

class WeatherService {
    /**
     * Fetch current weather data.
     *
     * Static method — ) {
        $response = wp_remote_get(
            'https://api.example.com/weather?city=London',
            [ 'timeout' => 10 ]
        );

        if ( is_wp_error( $response ) ) {
            error_log( '[my-plugin] Weather API error: ' . $response->get_error_message() );
            return [];
        }

        if ( 200 !== wp_remote_retrieve_response_code( $response ) ) {
            return [];
        }

        $body = wp_remote_retrieve_body( $response );
        $data = json_decode( $body, true );

        return is_array( $data ) ? $data : [];
    }
}


// my-plugin.php (or a service class loaded during init)
use Pattonwebz\WpStaleCache\CronHandler;
use Pattonwebz\WpStaleCache\StaleCache;
use MyPlugin\WeatherService;

add_action( 'init', function () {
    CronHandler::register();
} );

/**
 * Return weather data for London, served from cache wherever possible.
 *
 * - Hit within the first hour   → value returned instantly from wp_options.
 * - Hit in minutes 60–65        → stale value returned instantly;
 *                                  WP-Cron schedules a background refresh.
 * - Hit after 65 minutes        → synchronous regeneration on this request.
 *
 * @return array<string, mixed>
 */
function myplugin_get_weather() {
    static $cache = null;
    if ( null === $cache ) {
        $cache = new StaleCache( '_myplugin_' );
    }

    $weather = $cache->get(
        'weather_london',
        [ WeatherService::class, 'fetch_current' ], // serialisable for WP-Cron
        3600, // fresh for 1 hour
        300   // serve stale for 5 minutes while cron refreshes
    );

    return is_array( $weather ) ? $weather : [];
}

// Invalidate if a user manually triggers a cache clear from the admin.
add_action( 'admin_post_myplugin_clear_weather_cache', function () {
    $cache = new StaleCache( '_myplugin_' );
    $cache->forget( 'weather_london' );
    wp_safe_redirect( admin_url( 'options-general.php?page=myplugin&cleared=1' ) );
    exit;
} );