Download the PHP package pattonwebz/wp-stale-cache without Composer

On this page you can find all versions of the php package pattonwebz/wp-stale-cache. It is possible to download/install these versions without Composer. Possible dependencies are resolved automatically.

FAQ

After the download, you have to make one include require_once('vendor/autoload.php');. After that you have to import the classes with use statements.

Example:
If you use only one package a project is not needed. But if you use more then one package, without a project it is not possible to import the classes with use statements.

In general, it is recommended to use always a project to download your libraries. In an application normally there is more than one library needed.
Some PHP packages are not free to download and because of that hosted in private repositories. In this case some credentials are needed to access such packages. Please use the auth.json textarea to insert credentials, if a package is coming from a private repository. You can look here for more information.

  • Some hosting areas are not accessible by a terminal or SSH. Then it is not possible to use Composer.
  • To use Composer is sometimes complicated. Especially for beginners.
  • Composer needs much resources. Sometimes they are not available on a simple webspace.
  • If you are using private repositories you don't need to share your credentials. You can set up everything on our site and then you provide a simple download link to your team member.
  • Simplify your Composer build process. Use our own command line tool to download the vendor folder as binary. This makes your build process faster and you don't need to expose your credentials for private repositories.
Please rate this library. Is it a good library?

Informations about the package wp-stale-cache

wp-stale-cache

Stale-while-revalidate caching for WordPress using the Options API and WP-Cron.

What it does

Instead of letting your cache expire and forcing a slow synchronous regeneration on every miss, wp-stale-cache keeps serving the last known value while quietly refreshing it in the background.

Three states:

State Condition Behaviour
Fresh now < expires_at Return cached value immediately.
Stale expires_at ≤ now < expires_at + stale_offset Return old value instantly; schedule a background WP-Cron refresh.
Expired now ≥ expires_at + stale_offset Regenerate synchronously, store, return fresh value.

Why Options, not Transients?

Most WordPress SWR cache libraries — including ryanhellyer/stale-cache and humanmade/hm-swr-cache — store their data in transients. That works for many use cases, but it comes with a silent failure mode: transients can be evicted.

When WordPress is running with an external object cache (Memcached, Redis, or any WP_Object_Cache drop-in), transients are stored in that layer rather than the database. Under memory pressure, the object cache backend is free to evict entries with no notice. Your cached data disappears. WordPress does not throw an error, log a warning, or return a meaningful signal — it just returns false from get_transient(). Your code regenerates synchronously, or worse, silently misses.

That is the expected behaviour of transients, they are transient after all.

WordPress options are different. update_option() writes to the wp_options database table unconditionally. A Redis flush, a Memcached restart, or a full object cache wipe does not remove an option. It survives because it lives in the database, not in a volatile memory layer.

wp-stale-cache is a persistent cache by design. That is the point. If you need a cache entry to survive a Redis flush, a Memcached restart, or a server reboot, use the default StaleCache class — it uses the Options API.

If you are comfortable with eviction risk — for example, you want object cache layer support and your data is cheap to regenerate — TransientStaleCache is available as an opt-in alternative (see Using the Transient Backend below). But it is not the default, and it does not reflect this package's design intent.

Requirements

Installation

WordPress itself is not a Composer package, so it is not listed as a dependency. Ensure WordPress is loaded before using this library.

Quick start

1. Register the cron handler

Call this once during plugin or theme initialisation (e.g. functions.php):

2. Cache a value

The generator parameter must be serializable for the stale-cache path (see Generator Callable Constraints below). Use named functions or static array callables, not closures.

3. Invalidate on change

4. Flush by prefix

5. Check state without loading value

Generator Callable Constraints (Serialization for WP-Cron)

When cache is fresh or expired, the generator runs immediately on the current request — any callable works fine (closures, named functions, static methods, instance methods).

When cache is stale, the generator is passed to wp_schedule_single_event() for background refresh. WordPress serializes this callable into wp_options for deferred execution on a future HTTP request. Only serializable callables survive this round-trip:

Recommended approach: Always use static array callables ([ClassName::class, 'method']) for generators to guarantee correct behaviour on all cache paths. If you only ever use this package for immediate (non-stale) cache, closures would work — but that is risky because you cannot always predict which path (fresh/stale/expired) will fire on a given request.

Custom prefix

Pass a prefix string to the constructor to namespace your cache entries:

Storage

Each cache key creates two rows in wp_options:

Option name Contains
_wpsc_{key} The cached value
_wpsc_{key}_meta ['expires_at' => int, 'stale_offset' => int]

Both options are stored with autoload = false to avoid loading them on every page.

Tradeoffs

The two-option design provides persistence and stale-while-revalidate guarantees, but comes with a cost: every get(), set(), and remove() operation requires two database lookups or writes — one for the value, one for the metadata.

This makes wp-stale-cache best suited for longer-lived cached items — hours or days — where the overhead of two DB operations is negligible compared to the benefit of persistent stale-while-revalidate behaviour and surviving object cache evictions.

It is not ideal for:

For those use cases, consider using WordPress transients directly or TransientStaleCache (see Using the Transient Backend below).

Not suitable for

Using the Transient Backend

TransientStaleCache provides the same public API as StaleCache but stores data using set_transient / get_transient / delete_transient instead of the Options API. Use it if you specifically want your cache to live in the object cache layer — for example, when you are fine with the data being regenerated on eviction and you want the performance characteristics of Memcached or Redis. The trade-off is clear: entries may be silently evicted by the object cache backend under memory pressure. Do not use this class for anything that must survive a Redis flush or a Memcached restart.

Note: TransientStaleCache does not implement a flush() method. WordPress provides no native way to query transients by prefix without a direct database query, and that is intentionally deferred to a future version.

Optional Logging

wp-stale-cache has zero required dependencies beyond PSR-3 interfaces. For logging cache events and background refresh lifecycle, install the optional PSR-3 logger:

Then inject it:

For background refresh logging, wire the logger into CronHandler too:

Any PSR-3 compatible logger works — not just pattonwebz/psr3-logger. If no logger is injected, all logging is silently suppressed.

Examples

The examples below use PHP 7.4-compatible positional arguments. Important: The generator callable must be serializable (named function, static method, or object method with __sleep) because stale-cache entries are refreshed via WP-Cron, which serializes the callable for deferred execution. See Generator Callable Constraints above for details.


1. Basic usage

Register the cron handler once during plugin or theme boot, then call get() with a generator callable, a TTL (fresh window), and a stale offset (background-refresh window).


2. Custom prefix — namespace per plugin or theme

Pass a unique prefix string so your keys never collide with another plugin's or the default _wpsc_ namespace.

You can create multiple instances with different prefixes in the same project to keep caches logically separated:


3. Explicit cache busting — forget() and flush()

Use forget() to invalidate a single key and flush() to wipe all keys under a prefix.

You can also inspect whether a key is already stale before deciding to bust it:


4. Transient backend — TransientStaleCache as a drop-in alternative

TransientStaleCache exposes the same get(), forget(), and get_state() methods as StaleCache. Swap the class name to store data in transients instead of wp_options. The trade-off: entries may be silently evicted by the object cache under memory pressure.

Choose TransientStaleCache when:


5. Real-world scenario — caching an external API response

The following example caches a remote weather API call for 1 hour and serves stale data for 5 minutes while WP-Cron regenerates it silently in the background. The generator is a named static method so it can be serialised for cron scheduling.

Licence

MIT — © William Patton


All versions of wp-stale-cache with dependencies

PHP Build Version
Package Version
Requires php Version ^7.4
ext-json Version *
psr/log Version ^1.1
Composer command for our command line client (download client) This client runs in each environment. You don't need a specific PHP version etc. The first 20 API calls are free. Standard composer command

The package pattonwebz/wp-stale-cache contains the following files

Loading the files please wait ...