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:
- Filters for classes extending
AbstractApivalkController. - Calls the static
getRoute()method on each discovered controller. - 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: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.