Skip to main content

Core Components

The cache system consists of several interoperating classes:

RouterCacheInterface

A simple interface that defines the contract for any router cache implementation. It must provide a getRouterCacheCollection() method.

RouterCacheCollection

An internal collection of RouterCacheEntry objects. It is responsible for:
  • Converting route path templates (e.g., /users/{id}) into optimized regular expressions (e.g., #^/users/([a-zA-Z0-9_-]+)$#).
  • Providing an efficient search space for the Router.

RouterCacheEntry

A small data object that links a Route definition, its compiled regex, and its associated AbstractApivalkController class name.

RouterFilesystemCache

This is the standard implementation of the router cache. It automates the entire route registration process.

Automated Discovery

When the cache is empty or expired, RouterFilesystemCache uses the ClassLocator to scan a directory for PHP classes. It then:
  1. Filters for classes extending AbstractApivalkController.
  2. Calls the static getRoute() method on each discovered controller.
  3. Assembles a RouterCacheCollection.

Persistence

The collection is serialized to JSON and saved to a temporary file on the filesystem. This ensures that the expensive scanning and regex compilation logic only runs once per cache lifetime.

Configuration

You can configure the cache location and lifetime during instantiation:
use apivalk\apivalk\Router\Cache\RouterFilesystemCache;
use apivalk\apivalk\Util\ClassLocator;

$locator = new ClassLocator('/path/to/controllers', 'App\\Controllers');
$cache = new RouterFilesystemCache(
    '/path/to/cache/dir',
    $locator,
    3600 // Cache lifetime in seconds (default: 600)
);

Performance Considerations

  • Production: In production environments, set a high cache lifetime. This ensures that routing is near-instant as it only involves reading a single JSON file from disk.
  • Development: During development, you may want to set a shorter lifetime or clear the cache directory manually when adding new routes.
  • Atomic Operations: The cache system handles directory creation and file writing safely to prevent issues under concurrent load.