Zero-Latency Serving

CacheHandler

Bypass database queries and view rendering logic by serving static HTML snapshots. The CacheHandler creates a file-based cache layer that drastically reduces TTFB (Time To First Byte).

Caching Logic Matrix

Prisma PHP determines whether to cache a request based on the interaction between your .env global settings and route-specific overrides.

Global (CACHE_ENABLED) Route ($isCacheable) Result
"false" null (default) No Cache
"false" true Force Cache
"false" false No Cache
"true" null (default) Cache All
"true" false Skip Route

Configuration

Global Environment

Define defaults in your .env file.

# .env

# Enable system-wide caching
CACHE_ENABLED="true"

# Default TTL (600 = 10 minutes)
CACHE_TTL="600"

Route Overrides

Control caching behavior per route in your controller or entry file.

<?php

use PP\CacheHandler;

// Force cache this specific page
CacheHandler::$isCacheable = true;

// Set specific TTL (e.g., 10 seconds)
// This overrides the global default
CacheHandler::$ttl = 10;
?>

API Reference

static serveCache(string $uri, int $defaultTtl = 600): void

Attempts to serve a static file for the given URI. If a valid, non-expired cache file exists, it outputs the content and terminates script execution.

Behavior

  • Checks PrismaPHPSettings for route-specific TTL first.
  • Falls back to $defaultTtl if no route config exists.
  • Appends an HTML comment: <!-- Cached copy generated at: ... -->
static invalidateByUri(string|array $uris): void

Intelligently removes cache files for one or more specific routes. Accepts leading slashes or plain paths.

<?php

use PP\CacheHandler;

// Invalidate single route
CacheHandler::invalidateByUri('/blog');

// Invalidate multiple routes (e.g., after updating user profile)
CacheHandler::invalidateByUri([
    '/',
    '/users',
    '/dashboard'
]);
?>
static resetCache(?string $uri = null): void

Low-level cache clearing method.

  • null Purges ALL files in the cache directory.
  • $uri Deletes the specific file for that route.

Practical Workflows

content Update Strategy

When saving dynamic content (like a blog post), you must clear the relevant cache to ensure users see the latest data immediately.

public function savePost($data) {
    // 1. Save to Database
    $this->db->insert('posts', $data);

    // 2. Clear relevant caches
    CacheHandler::invalidateByUri([
        '/blog',          // The index listing
        '/blog/recent'    // Maybe a widget
    ]);

    return "Saved successfully";
}

Concurrency Safety

saveCache uses LOCK_EX by default. This prevents race conditions where two requests try to write the cache file simultaneously.

Storage Location

Files are stored in DOCUMENT_PATH . '/caches'. Ensure this directory is writable by your web server user (e.g., www-data).