> ## Documentation Index
> Fetch the complete documentation index at: https://docs.apivalk.com/llms.txt
> Use this file to discover all available pages before exploring further.

# PhpFileCache

> Store the route index as PHP files so OPcache serves it from shared memory, with no file reads and no JSON decoding per request.

`PhpFileCache` writes every cache item as a PHP file that returns an array. OPcache compiles that file once and keeps it in shared memory, so a warm read costs neither file I/O nor JSON decoding. Under PHP-FPM, where every request builds the router anew, that is the difference between reading and decoding the route index on every request and getting it for free.

## When to use it

Use it for data that is **written rarely and read on every request**, above all the router cache:

```php theme={null}
use apivalk\apivalk\Cache\FilesystemCache;
use apivalk\apivalk\Cache\PhpFileCache;
use apivalk\apivalk\Router\Router;
use apivalk\apivalk\Util\ClassLocator;

$router = new Router(
    new ClassLocator(__DIR__ . '/src/Http/Controller', 'App\\Http\\Controller'),
    new PhpFileCache(__DIR__ . '/var/cache/routes', 3600)
);

// Rate limit counters change on every request; keep them in another cache.
$rateLimitCache = new FilesystemCache(__DIR__ . '/var/cache/rate-limit');
```

Keep frequently changing data, such as rate limit counters, in `FilesystemCache` or a memory store. Every write invalidates the OPcache entry of that file, so a value that changes on every request gains nothing and keeps OPcache busy.

In a [FrankenPHP worker](https://docs.apivalk.com/how-to/frankenphp-worker.md) the router already keeps the decoded index in memory, so `PhpFileCache` mainly pays off for the first request of every worker and under FPM.

## What it stores

Only scalars, arrays and `null`, because the file is generated with `var_export()`. Setting an item whose value contains an object throws an `InvalidArgumentException`. The route index, the serialized routes and the JWKS key set all fit.

## Requirements and safety

* OPcache is part of every PHP 8.5 build. Make sure it is enabled for your SAPI, otherwise every read includes and compiles the file.
* Files are named `<sha256 of the key>.cache.php`; `clear()` only removes files with that suffix, so a shared directory is safe.
* **Whoever can write to the cache directory can run code.** Keep it outside the web root and writable only by the PHP user. A directory `PhpFileCache` creates itself gets mode `0750`.
* Writes, misses and `increment()` behave like in [FilesystemCache](https://docs.apivalk.com/cache/filesystem-cache.md): atomic renames under a random temporary name, a vanished or corrupt file is a miss (a corrupt one is removed), an existing file that cannot be read throws a `RuntimeException`, and increments are serialised by `.increment.lock` in the cache directory.


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.