CacheHandler

The CacheHandler class enables file-based caching for application routes by storing and serving static HTML files. This helps reduce server load and improve response times for frequently accessed pages.

Purpose

It checks whether a cache file exists, if it's valid based on the TTL (time-to-live), and serves it if possible. It also allows saving new cache content or resetting specific or all cache files.

Cache is automatically bypassed for dynamic requests, such as those triggered by wire or secondary (AJAX) calls. In these cases, Prisma PHP serves the live, non-cached version of the response to ensure dynamic content is always up to date.

Static Properties

  • static bool $isCacheable: Enables or disables caching for the current request. Default is true.
  • static int $ttl: Custom time-to-live (in seconds) for the cache of the current request. Default is 0.

Methods

  • serveCache(string $uri, int $defaultTtl = 600): Attempts to serve a cached file for the given URI, if it exists and hasn’t expired.
  • saveCache(string $uri, string $content, bool $useLock = true): Saves a cache file for the given URI with the specified content.
  • resetCache(?string $uri = null): Deletes a specific cache file or clears the entire cache directory if no URI is provided.

Environment Configuration

To enable or configure caching globally, update your .env file:

# APP CACHE ENABLED - Set to true to enable caching - Default is false
CACHE_ENABLED="false"

# APP CACHE TTL - Set the cache time to live in seconds - Default is 600 (10 minutes)
CACHE_TTL="600"

Per-Page Caching

To customize caching on specific pages, include the following at the top of the route file:

<?php
use Lib\CacheHandler;

// Enable or disable cache for this specific route
CacheHandler::$isCacheable = true;

// Set custom TTL (in seconds) for this route
CacheHandler::$ttl = 10;
?>

Example: Save Page Content to Cache

<?php
use Lib\CacheHandler;

CacheHandler::saveCache(Request::$uri, $htmlContent);
?>

Example: Clear Cache

To clear a single cached page:

CacheHandler::resetCache('/about');

To clear all cached pages:

CacheHandler::resetCache();

Cache Directory

All cached HTML files are stored inside /caches under your DOCUMENT_PATH. If the directory does not exist, it will be created automatically.

Helpful Tip

You can combine route-level TTL control via PrismaPHPSettings::$includeFiles to define cache behaviors for each URI centrally.

For implementation details, refer to the file: src/Lib/CacheHandler.php.