CacheHandler
The CacheHandler reduces server load by generating static HTML snapshots of your routes. When a valid cache exists, Prisma PHP serves the file instantly, bypassing database queries and view rendering logic.
Caching Workflow
The handler automatically checks for dynamic contexts (like Wire requests) to prevent caching interactive states.
Configuration
Environment Settings
Set defaults in your .env file. This applies to all routes unless overridden.
# Enable Caching System
CACHE_ENABLED="true"
# Default TTL in seconds (600 = 10 minutes)
CACHE_TTL="600"
Route-Specific Overrides
You can control caching granularly inside your controller or route file.
<?php
use PP\CacheHandler;
// Explicitly enable cache for this heavy page
CacheHandler::$isCacheable = true;
// Cache for only 10 seconds (useful for semi-realtime dashboards)
CacheHandler::$ttl = 10;
?>
Key Methods
static serveCache(string $uri, int $defaultTtl = 600): void
Checks for a valid cache file. If found and not expired, it outputs the content and exits script execution immediately.
- Appends a comment:
<!-- Cached copy generated at: ... --> - Respects
PrismaPHPSettingsoverrides.
static saveCache(string $uri, string $content, bool $useLock = true): void
Writes the HTML content to the filesystem. Uses file locking (LOCK_EX) by default to prevent race conditions during high concurrency.
static resetCache(?string $uri = null): void
Invalidates cache.
- With URI: Deletes the specific file for that route.
- Without URI: Purges the entire cache directory.
Practical Usage
Manual Cache Busting
Useful when a user updates content (e.g., saving a blog post) and you need to ensure the frontend reflects the change immediately.
<?php
use PP\CacheHandler;
// ... save blog post logic ...
// Clear cache for the specific post
CacheHandler::resetCache('/blog/my-new-post');
// Optionally clear the blog index too
CacheHandler::resetCache('/blog');
?>
📂 Storage Location
Cache files are stored in DOCUMENT_PATH . '/caches'. Ensure your web server has write permissions to this directory.