diff --git a/README.md b/README.md index cd45a18..2c2855f 100644 --- a/README.md +++ b/README.md @@ -91,7 +91,7 @@ $cache->get('user:42'); | `increment(string $key, int $offset = 1)` | `int` | Add to a counter and return the new value. | | `decrement(string $key, int $offset = 1)` | `int` | Subtract from a counter and return the new value. | -See [`docs/`](docs/README.md) for the full guide, including per-handler +See [`docs/`](docs/Home.md) for the full guide, including per-handler configuration and the exact semantics of TTLs, keys and counters. ## Notes @@ -100,24 +100,30 @@ configuration and the exact semantics of TTLs, keys and counters. `DateInterval` sets a lifetime; a zero or negative TTL deletes the item. - **Keys:** any non-empty string that does not contain the PSR-16 reserved characters `{}()/\@:`. An invalid key throws an - [`InvalidArgumentException`](docs/exceptions.md). -- **Counters:** `increment()`/`decrement()` treat a missing or non-numeric item - as `0` and store the result without an expiry. They behave identically across + [`InvalidArgumentException`](docs/Error-Handling.md). +- **Counters:** `increment()`/`decrement()` treat a missing item, or one that is not an + `int` or `float`, as `0` and store the result without an expiry. They behave identically across every handler. - **Values:** anything `serialize()` can handle round-trips exactly — including `null`, `false` and objects. ## Documentation -- [Getting started](docs/getting-started.md) -- [Configuration & options](docs/configuration.md) -- [PSR-16 behaviour & the handler API](docs/psr-16.md) -- Handlers: [File](docs/file-handler.md) · - [PDO](docs/pdo-handler.md) · - [Redis](docs/redis-handler.md) · - [Memcache(d)](docs/memcache-handler.md) · - [WinCache](docs/wincache-handler.md) -- [Exceptions](docs/exceptions.md) +- [Home](docs/Home.md) +- [Installation](docs/Installation.md) · [Quick Start](docs/Quick-Start.md) +- [The Cache Factory](docs/The-Cache-Factory.md) +- [Keys, TTL & Values](docs/Keys-TTL-and-Values.md) · + [Counters](docs/Counters.md) · + [Bulk Operations](docs/Bulk-Operations.md) +- [Configuration Options](docs/Configuration-Options.md) +- Handlers: [File](docs/File-Handler.md) · + [PDO](docs/PDO-Handler.md) · + [Redis](docs/Redis-Handler.md) · + [Memcache(d)](docs/Memcache-Handler.md) · + [WinCache](docs/WinCache-Handler.md) +- [Error Handling](docs/Error-Handling.md) · [API Reference](docs/API-Reference.md) +- [Recipes](docs/Recipes.md) · [Custom Handlers](docs/Custom-Handlers.md) · [Testing](docs/Testing.md) +- [FAQ](docs/FAQ.md) · [Troubleshooting](docs/Troubleshooting.md) ## Contributing diff --git a/docs/API-Reference.md b/docs/API-Reference.md new file mode 100644 index 0000000..a51ce14 --- /dev/null +++ b/docs/API-Reference.md @@ -0,0 +1,193 @@ +# API Reference + +Every public member of `initphp/cache`. For narrative explanations, follow the +links into the concept pages. + +--- + +## `Cache` (factory) + +`InitPHP\Cache\Cache` — see [The Cache Factory](The-Cache-Factory.md). + +### `create()` + +```php +public static function create( + string|CacheInterface $handler, + array $options = [] +): CacheInterface +``` + +Builds (or accepts) a handler, applies `$options`, and returns it. + +- `$handler` — a handler **class name** to instantiate, or an already-built + handler **instance**. +- `$options` — handler options, keys matched case-insensitively. +- **Throws** [`CacheException`](#cacheexception) if the class does not exist, does + not implement `CacheInterface`, or the runtime does not support it. + +--- + +## `CacheInterface` + +`InitPHP\Cache\CacheInterface extends Psr\SimpleCache\CacheInterface`. + +The eight PSR-16 methods plus five InitPHP extensions. Every handler implements +this interface. + +### PSR-16 methods + +```php +public function get(string $key, mixed $default = null): mixed; +``` +Return the value for `$key`, or `$default` (returned as-is) on a miss. +**Throws** [`InvalidArgumentException`](#invalidargumentexception) for an invalid +key. See [Keys, TTL & Values](Keys-TTL-and-Values.md). + +```php +public function set(string $key, mixed $value, null|int|DateInterval $ttl = null): bool; +``` +Store `$value`. `$ttl`: `null` = forever, seconds, or a `DateInterval`; `0`/ +negative deletes the item. Returns `true` on success. See +[TTL](Keys-TTL-and-Values.md#time-to-live-ttl). + +```php +public function delete(string $key): bool; +``` +Remove one item. Deleting a missing key still succeeds. + +```php +public function clear(): bool; +``` +Remove every item this handler owns. Scope differs per handler — File/PDO honour +the `prefix`; Redis/Memcache/WinCache flush the whole store. See each handler +page. + +```php +public function has(string $key): bool; +``` +Whether a live (non-expired) item exists. Use this to distinguish a stored `null` +from a miss. + +```php +public function getMultiple(iterable $keys, mixed $default = null): iterable; +``` +Map of `key => value`, with `$default` for misses. See +[Bulk Operations](Bulk-Operations.md). + +```php +public function setMultiple(iterable $values, null|int|DateInterval $ttl = null): bool; +``` +Store many `key => value` pairs with one TTL. `true` only if all succeed. + +```php +public function deleteMultiple(iterable $keys): bool; +``` +Delete many keys. `true` only if all succeed. + +### InitPHP extensions + +```php +public function setOptions(array $options = []): static; +``` +Merge options (case-insensitively) into the handler; returns `$this`. + +```php +public function getOption(string $key, mixed $default = null): mixed; +``` +Read one option (case-insensitive lookup), or `$default` when unset. + +```php +public function isSupported(): bool; +``` +Whether the current runtime can use this handler (e.g. the extension is loaded). + +

increment() / decrement()

+ +```php +public function increment(string $key, int $offset = 1): int; +public function decrement(string $key, int $offset = 1): int; +``` +Adjust an integer counter and return the **new value**. A missing item, or one that is not an int or float, +counts as `0`; the result is stored without an expiry. Identical on every +handler, **not** atomic across processes. See [Counters](Counters.md). + +--- + +## `BaseHandler` + +`InitPHP\Cache\BaseHandler implements CacheInterface` — the abstract base every +built-in handler extends. Relevant when [writing your own handler](Custom-Handlers.md). + +### Constant + +```php +public const RESERVED_CHARACTERS = '{}()/\@:'; +``` +The PSR-16 characters a key may not contain. + +### Methods a subclass must implement + +`get()`, `set()`, `delete()`, `clear()`, `has()`, `isSupported()` — the +storage-specific primitives. (`increment()`, `decrement()`, the `*Multiple()` +methods, options handling and key/TTL helpers are provided.) + +### Protected helpers for subclasses + +```php +protected function name(string $key): string; +``` +Validate `$key` and return it prefixed with the `prefix` option — the physical +storage key. Throws [`InvalidArgumentException`](#invalidargumentexception) for an +invalid key. + +```php +protected function validateKey(string $key): string; +``` +Validate a key without prefixing it (returns it unchanged, or throws). + +```php +protected function ttlToSeconds(null|int|DateInterval $ttl): ?int; +``` +Normalise a PSR-16 TTL to seconds (`null` = no expiry). A `DateInterval` is +resolved from now; the result may be zero/negative ("already expired"). + +```php +protected function optionInt(string $key, int $default = 0): int; +protected function optionFloat(string $key, float $default = 0.0): float; +protected function optionString(string $key, string $default = ''): string; +``` +Read an option coerced to a scalar type, falling back to `$default` when the +stored value is not coercible. + +--- + +## Exceptions + +`InitPHP\Cache\Exception\*` — see [Error Handling](Error-Handling.md). + +### `CacheException` + +```php +class CacheException + extends \Exception + implements \Psr\SimpleCache\CacheException +``` +Configuration and backend errors (missing extension, connection failure, missing +File `path`, invalid PDO `table`, bad factory class). + +### `InvalidArgumentException` + +```php +class InvalidArgumentException + extends \InvalidArgumentException + implements \Psr\SimpleCache\InvalidArgumentException +``` +An invalid cache key (empty, or containing a reserved character). Because the PSR +interface extends `Psr\SimpleCache\CacheException`, this is also catchable as a +`CacheException`. + +## Next steps + +- [Error Handling](Error-Handling.md) — the exception model in depth. +- [Custom Handlers](Custom-Handlers.md) — using the `BaseHandler` helpers above. diff --git a/docs/Bulk-Operations.md b/docs/Bulk-Operations.md new file mode 100644 index 0000000..ab24e41 --- /dev/null +++ b/docs/Bulk-Operations.md @@ -0,0 +1,116 @@ +# Bulk Operations + +Three PSR-16 methods read, write or delete many items in one call. They are +convenience wrappers — each one loops over the single-item methods — but they +keep call sites tidy and accept any `iterable`. + +```php +public function getMultiple(iterable $keys, mixed $default = null): iterable; +public function setMultiple(iterable $values, null|int|DateInterval $ttl = null): bool; +public function deleteMultiple(iterable $keys): bool; +``` + +## `getMultiple()` + +Returns a map keyed by the requested keys, with `$default` for every miss: + +```php +$cache->set('a', 1); +$cache->set('b', 2); + +$cache->getMultiple(['a', 'b', 'missing']); +// ['a' => 1, 'b' => 2, 'missing' => null] + +$cache->getMultiple(['a', 'missing'], 0); +// ['a' => 1, 'missing' => 0] +``` + +## `setMultiple()` + +Stores every pair, with one shared TTL (same rules as +[`set()`](Keys-TTL-and-Values.md#time-to-live-ttl)). Returns `true` only when +**every** write succeeded: + +```php +$cache->setMultiple([ + 'a' => 1, + 'b' => 2, + 'c' => 3, +], 600); // all three expire in 600 seconds → true +``` + +An empty input is a successful no-op: + +```php +$cache->setMultiple([]); // true +``` + +## `deleteMultiple()` + +Removes every key; returns `true` only when **every** delete succeeded: + +```php +$cache->deleteMultiple(['a', 'b', 'c']); // true +$cache->deleteMultiple([]); // true (nothing to do) +``` + +> Deleting a key that does not exist counts as success — the post-condition +> ("the key is gone") already holds. + +## Any iterable works + +PSR-16 requires `iterable`, so arrays, Generators and other `Traversable`s are +all accepted. This is handy for streaming a large key set without building an +array: + +```php +function keysToWarm(): Generator +{ + yield 'home'; + yield 'about'; + yield 'pricing'; +} + +$pages = $cache->getMultiple(keysToWarm(), null); +``` + +For `setMultiple()` the iterable yields `key => value` pairs: + +```php +function pairs(): Generator +{ + foreach (fetch_rows() as $row) { + yield 'row_' . $row['id'] => $row; + } +} + +$cache->setMultiple(pairs(), 3600); +``` + +## Keys are still validated + +Each key goes through the same validation as the single-item methods, so an +invalid key in the set throws an +[`InvalidArgumentException`](Error-Handling.md): + +```php +$cache->getMultiple(['ok', 'bad:key']); // throws — ":" is reserved +``` + +> Because the methods iterate, a throw can happen part-way through. Validate +> untrusted keys up front (or hash them — see +> [Keys, TTL & Values](Keys-TTL-and-Values.md#practical-key-advice)) if you need +> all-or-nothing behaviour. + +## Performance note + +These helpers loop over the single-item operations rather than issuing one +batched backend command. They reduce code, not round-trips. For very large, +latency-sensitive batch loads against [Redis](Redis-Handler.md) or +[Memcache(d)](Memcache-Handler.md), a native multi-get may be faster — reach for the +underlying client in that hot path. + +## Next steps + +- [Keys, TTL & Values](Keys-TTL-and-Values.md) — per-item rules these inherit. +- [API Reference](API-Reference.md) — exact signatures and return types. diff --git a/docs/Configuration-Options.md b/docs/Configuration-Options.md new file mode 100644 index 0000000..86f2365 --- /dev/null +++ b/docs/Configuration-Options.md @@ -0,0 +1,112 @@ +# Configuration Options + +Options are passed to [`Cache::create()`](The-Cache-Factory.md) (or a handler +constructor) as an associative array. **Keys are matched case-insensitively**, so +`prefix`, `Prefix` and `PREFIX` are the same option. Anything you omit falls back +to the default. + +```php +$cache = Cache::create(File::class, [ + 'path' => __DIR__ . '/var/cache', + 'prefix' => 'app_', +]); + +$cache->getOption('prefix'); // "app_" +$cache->getOption('mode', 0640); // 0640 (default returned when unset) +$cache->setOptions(['prefix' => 'v2_']); // merge more in; returns $this +``` + +## Shared option — every handler + +| Option | Type | Default | Description | +| --- | --- | --- | --- | +| `prefix` | `string` | `cache_` | Prepended to every key after validation; scopes `clear()` on the File and PDO handlers. Set to `''` to disable. | + +## [File](File-Handler.md) + +| Option | Type | Default | Description | +| --- | --- | --- | --- | +| `path` | `string` | _(required)_ | Directory the cache files live in. Must exist and be writable. | +| `mode` | `int\|null` | `0640` | `chmod()` mode per file; `null` skips `chmod()`. | + +```php +Cache::create(File::class, [ + 'path' => __DIR__ . '/var/cache', + 'mode' => 0600, + 'prefix' => 'app_', +]); +``` + +## [PDO](PDO-Handler.md) + +| Option | Type | Default | Description | +| --- | --- | --- | --- | +| `dsn` | `string` | `mysql:host=localhost;dbname=test` | PDO connection DSN. | +| `username` | `string\|null` | `null` | Connection user. | +| `password` | `string\|null` | `null` | Connection password. | +| `charset` | `string` | `utf8mb4` | MySQL only (`SET NAMES`). | +| `collation` | `string` | `utf8mb4_general_ci` | MySQL only. | +| `table` | `string` | `cache` | Table name; must match `[A-Za-z0-9_]+`. | + +```php +Cache::create(PDO::class, [ + 'dsn' => 'pgsql:host=127.0.0.1;dbname=app', + 'username' => 'app', + 'password' => 'secret', + 'table' => 'app_cache', +]); +``` + +## [Redis](Redis-Handler.md) + +| Option | Type | Default | Description | +| --- | --- | --- | --- | +| `host` | `string` | `127.0.0.1` | Server host. | +| `port` | `int` | `6379` | Server port. | +| `timeout` | `int\|float` | `0` | Connection timeout in seconds (`0` = unlimited). | +| `password` | `string\|null` | `null` | `AUTH` password; skipped when `null`. | +| `database` | `int\|null` | `0` | Database index to `SELECT`. | + +```php +Cache::create(Redis::class, [ + 'host' => 'redis.internal', + 'port' => 6379, + 'database' => 3, + 'timeout' => 1.5, +]); +``` + +## [Memcache(d)](Memcache-Handler.md) + +| Option | Type | Default | Description | +| --- | --- | --- | --- | +| `host` | `string` | `127.0.0.1` | Server host. | +| `port` | `int` | `11211` | Server port. | +| `weight` | `int` | `1` | Server weight (Memcached only). | +| `default_ttl` | `int` | `0` | TTL used when `set()` gets no TTL. `0` = no expiry. | + +```php +Cache::create(Memcache::class, [ + 'host' => 'memcached.internal', + 'port' => 11211, + 'default_ttl' => 300, +]); +``` + +## [WinCache](WinCache-Handler.md) — _deprecated_ + +| Option | Type | Default | Description | +| --- | --- | --- | --- | +| `default_ttl` | `int` | `0` | TTL used when `set()` gets no TTL. `0` = no expiry. | + +## Notes on types + +- Numeric options are coerced leniently: a numeric string like `'6379'` is + accepted for an integer option. A non-numeric value falls back to the default. +- `path` and the PDO `table` are validated and will throw a + [`CacheException`](Error-Handling.md) if missing/invalid — see each handler page. + +## Next steps + +- [The Cache Factory](The-Cache-Factory.md) — how options are applied and merged. +- The individual handler pages for the meaning and edge cases of each option. diff --git a/docs/Counters.md b/docs/Counters.md new file mode 100644 index 0000000..2d89fc3 --- /dev/null +++ b/docs/Counters.md @@ -0,0 +1,103 @@ +# Counters + +`increment()` and `decrement()` adjust an integer counter and return the **new +value**. They are an InitPHP extension on top of PSR-16 (declared on +[`CacheInterface`](API-Reference.md#cacheinterface)), and they behave **identically +on every handler**. + +```php +public function increment(string $key, int $offset = 1): int; +public function decrement(string $key, int $offset = 1): int; +``` + +## Basic use + +```php +$cache->increment('views'); // 1 (key was missing → starts at 0) +$cache->increment('views'); // 2 +$cache->increment('views', 10); // 12 +$cache->decrement('views', 5); // 7 +$cache->get('views'); // 7 — readable as a normal value +``` + +## The contract + +The behaviour is the same for File, PDO, Redis, Memcache and WinCache: + +- A **missing item, or one that is not an `int` or `float`,** is treated as `0`, so the result equals the + offset: + ```php + $cache->increment('fresh', 5); // 5 (was missing) + + $cache->set('label', 'hello'); + $cache->increment('label', 3); // 3 (not an int or float → reset to 0, then +3) + ``` +- The **new integer value is returned**. +- The result is **stored without an expiry**. Incrementing a key that had a TTL + drops that TTL. +- `decrement($key, $n)` is exactly `increment($key, -$n)`, so counters can go + negative: + ```php + $cache->set('stock', 3); + $cache->decrement('stock', 5); // -2 + ``` + +## Not atomic across processes + +These counters are implemented once in [`BaseHandler`](Custom-Handlers.md) as a +**read-modify-write** over `get()` / `set()`. That makes them uniform and +compatible with values written by `set()`, but it means they are **not atomic** +under concurrency: two processes incrementing the same key at the same instant +can race and lose an update. + +For most caches (page-view counters, soft rate limits, metrics) that is fine. If +you need strict atomic counters under heavy concurrency, use your backend's +native facility directly — for example phpredis `INCRBY`: + +```php +// Direct, atomic Redis counter (bypasses this library's envelope format) +$redis = new \Redis(); +$redis->connect('127.0.0.1', 6379); +$redis->incrBy('atomic:counter', 1); +``` + +> Keep such native counters in their **own keyspace**. A value written with the +> library's `set()` is a serialised envelope, not a bare integer, so the two +> styles must not share a key. + +## Counters and TTL: a soft rate limiter + +Because `increment()` stores **without an expiry**, it is not a drop-in tool for +a time-windowed limit: the first increment after a `set($key, 0, $window)` would +drop the window. For a soft fixed-window limiter, manage the window yourself with +`get()` / `set()` and a key that rotates per window: + +```php +function rateLimit(CacheInterface $cache, string $ip, int $max, int $window): bool +{ + // The key changes every $window seconds, so each window self-expires. + $bucket = (int) floor(time() / $window); + $key = 'rate_' . hash('xxh3', $ip) . '_' . $bucket; + + $count = (int) $cache->get($key, 0) + 1; + $cache->set($key, $count, $window); // re-set with the window TTL each hit + + return $count <= $max; +} + +if (!rateLimit($cache, $clientIp, 100, 60)) { + http_response_code(429); + exit('Too Many Requests'); +} +``` + +This stays correct with the library's semantics (the TTL lives on the `set()`, +not on `increment()`), though it shares the same non-atomic caveat — fine for a +soft limit. For a hard limit, use a native atomic counter with an expiry, e.g. +phpredis `INCR` + `EXPIRE`. + +## Next steps + +- [Keys, TTL & Values](Keys-TTL-and-Values.md) — how TTLs and values behave. +- [Recipes](Recipes.md) — more practical patterns. +- [API Reference](API-Reference.md#initphp-extensions) — the method signatures. diff --git a/docs/Custom-Handlers.md b/docs/Custom-Handlers.md new file mode 100644 index 0000000..64ee717 --- /dev/null +++ b/docs/Custom-Handlers.md @@ -0,0 +1,205 @@ +# Custom Handlers + +The five built-in handlers are not special — they extend +[`BaseHandler`](API-Reference.md#basehandler), which provides everything except the +storage primitives. Writing your own backend (APCu, DynamoDB, an in-memory store +for tests…) means implementing **six methods** and declaring your defaults. + +## What `BaseHandler` gives you + +You inherit, for free: + +- option handling (`getOption`, `setOptions`, the `prefix` default, the + `optionInt`/`optionFloat`/`optionString` helpers); +- key validation and prefixing via `$this->name($key)`; +- TTL normalisation via `$this->ttlToSeconds($ttl)`; +- the bulk methods `getMultiple` / `setMultiple` / `deleteMultiple`; +- the `increment()` / `decrement()` counters. + +You implement the six abstract methods: `get`, `set`, `delete`, `clear`, `has`, +`isSupported`. + +## A minimal in-memory handler + +Dependency-free, complete, and handy for tests (see [Testing](Testing.md)): + +```php + */ + private array $store = []; + + public function get(string $key, mixed $default = null): mixed + { + $name = $this->name($key); // validates + prefixes + if (!$this->alive($name)) { + return $default; + } + return $this->store[$name]['value']; + } + + public function set(string $key, mixed $value, null|int|DateInterval $ttl = null): bool + { + $name = $this->name($key); + $seconds = $this->ttlToSeconds($ttl); // null | int (may be <= 0) + + if ($seconds !== null && $seconds <= 0) { + unset($this->store[$name]); // expired-on-write → delete + return true; + } + + $this->store[$name] = [ + 'expires' => $seconds === null ? null : time() + $seconds, + 'value' => $value, + ]; + return true; + } + + public function delete(string $key): bool + { + unset($this->store[$this->name($key)]); + return true; + } + + public function clear(): bool + { + $this->store = []; + return true; + } + + public function has(string $key): bool + { + return $this->alive($this->name($key)); + } + + public function isSupported(): bool + { + return true; + } + + private function alive(string $name): bool + { + if (!isset($this->store[$name])) { + return false; + } + $expires = $this->store[$name]['expires']; + if ($expires !== null && $expires < time()) { + unset($this->store[$name]); + return false; + } + return true; + } +} +``` + +Use it like any built-in handler: + +```php +use InitPHP\Cache\Cache; + +$cache = Cache::create(App\Cache\ArrayHandler::class, ['prefix' => 'test_']); +$cache->set('k', 'v'); +$cache->get('k'); // "v" +``` + +## A real-world example: APCu + +Declare defaults in `$handlerOptions`, gate availability in `isSupported()`, and +lean on the helpers: + +```php + */ + protected array $handlerOptions = [ + 'default_ttl' => 0, // 0 = no expiry, used when set() gets no TTL + ]; + + public function get(string $key, mixed $default = null): mixed + { + $value = apcu_fetch($this->name($key), $ok); + return $ok ? $value : $default; + } + + public function set(string $key, mixed $value, null|int|DateInterval $ttl = null): bool + { + $name = $this->name($key); + $seconds = $this->ttlToSeconds($ttl); + + if ($seconds !== null && $seconds <= 0) { + apcu_delete($name); // already-expired → delete + return true; + } + if ($seconds === null) { + $seconds = $this->optionInt('default_ttl', 0); + } + return apcu_store($name, $value, $seconds); + } + + public function delete(string $key): bool + { + apcu_delete($this->name($key)); // a missing key still counts as deleted + return true; + } + + public function clear(): bool + { + return apcu_clear_cache(); // clears the whole APCu cache (not prefix-scoped) + } + + public function has(string $key): bool + { + return apcu_exists($this->name($key)); + } + + public function isSupported(): bool + { + return extension_loaded('apcu') && (bool) ini_get('apc.enabled'); + } +} +``` + +## Rules to follow + +To stay consistent with the built-in handlers and PSR-16: + +1. **Always run keys through `$this->name($key)`** — it validates (throwing + [`InvalidArgumentException`](Error-Handling.md) for bad keys) and applies the + prefix. +2. **Normalise TTLs with `$this->ttlToSeconds($ttl)`** and treat a `<= 0` result + as "delete the item, return `true`". +3. **`null` is a value, not a miss.** Make sure a stored `null` reads back as + `null` and `has()` returns `true` for it. (A serialised envelope, as Redis and + Memcache use, is the usual trick when the backend can't tell `false` from a + miss.) +4. **Return `bool` from `set`/`delete`/`clear`**, and the value (or the caller's + default) from `get`. +5. **Gate `isSupported()`** on whatever your backend needs; the + [factory](The-Cache-Factory.md) calls it and throws a `CacheException` when it + returns `false`. + +Get those right and the inherited `increment()`, `decrement()` and the +`*Multiple()` methods just work. + +## Next steps + +- [Testing](Testing.md) — use a custom in-memory handler in your test suite. +- [API Reference](API-Reference.md#basehandler) — every `BaseHandler` helper. diff --git a/docs/Error-Handling.md b/docs/Error-Handling.md new file mode 100644 index 0000000..c2eb343 --- /dev/null +++ b/docs/Error-Handling.md @@ -0,0 +1,130 @@ +# Error Handling + +The library throws exactly two exception types, both under +`InitPHP\Cache\Exception`. Each implements the matching PSR-16 interface, so you +can catch errors by the concrete class **or** through PSR. + +| Class | Extends | Implements (PSR-16) | Thrown for | +| --- | --- | --- | --- | +| `CacheException` | `\Exception` | `Psr\SimpleCache\CacheException` | configuration / backend errors | +| `InvalidArgumentException` | `\InvalidArgumentException` | `Psr\SimpleCache\InvalidArgumentException` | invalid cache keys | + +## `CacheException` + +Thrown for problems that are **not** about a bad argument: + +- a required extension is missing or disabled (building a handler); +- a backend connection / authentication / database selection fails + ([Redis](Redis-Handler.md), [Memcache(d)](Memcache-Handler.md), [PDO](PDO-Handler.md)); +- a required option is missing or invalid (the File [`path`](File-Handler.md), the + PDO [`table`](PDO-Handler.md)); +- the [factory](The-Cache-Factory.md) is given a class that does not exist or does + not implement `CacheInterface`. + +```php +use InitPHP\Cache\Cache; +use InitPHP\Cache\Handler\Redis; +use InitPHP\Cache\Exception\CacheException; + +try { + $cache = Cache::create(Redis::class, ['host' => 'redis.internal']); + $cache->set('k', 'v'); +} catch (CacheException $e) { + // log and fall back to another handler + error_log('Cache backend error: ' . $e->getMessage()); +} +``` + +## `InvalidArgumentException` + +Thrown when a cache key is **empty** or contains a character reserved by PSR-16 +(`{}()/\@:`). It is raised by every key-taking method (`get`, `set`, `delete`, +`has`, the `*Multiple` methods, `increment`, `decrement`). + +```php +use InitPHP\Cache\Exception\InvalidArgumentException; + +try { + $cache->get('bad:key'); // ":" is reserved +} catch (InvalidArgumentException $e) { + // the key came from somewhere untrusted +} +``` + +See [Keys, TTL & Values](Keys-TTL-and-Values.md#keys) for the full key rules. + +## One `catch` for everything + +`Psr\SimpleCache\InvalidArgumentException` extends +`Psr\SimpleCache\CacheException`, so an invalid-key error is **also** a +`CacheException`. To handle any library error in one place, catch the PSR base: + +```php +use Psr\SimpleCache\CacheException as PsrCacheException; + +try { + $cache->set($key, $value); +} catch (PsrCacheException $e) { + // any InitPHP\Cache error — invalid key or backend failure +} +``` + +Or catch the concrete classes when you want to react differently: + +```php +use InitPHP\Cache\Exception\CacheException; +use InitPHP\Cache\Exception\InvalidArgumentException; + +try { + $value = $cache->get($key); +} catch (InvalidArgumentException $e) { + // 400-style: the caller supplied a bad key +} catch (CacheException $e) { + // 500-style: a configuration or backend problem +} +``` + +## What does *not* throw + +PSR-16 reserves exceptions for invalid arguments and genuine failures. Ordinary +runtime hiccups are reported through return values instead: + +- A **cache miss** returns the `$default` (or `null`), not an exception. +- A failed **write/delete** generally returns `false`. For example, the + [PDO handler](PDO-Handler.md#errors) returns `false` on a query-level error (such + as a missing table) rather than throwing — only the **connection** failure + throws. + +This lets you treat the cache as best-effort: + +```php +// A failed set() degrades gracefully — the value just isn't cached. +if (!$cache->set('report', $report, 3600)) { + error_log('Could not cache the report; serving it uncached.'); +} +``` + +## Failing soft on an unavailable backend + +A common production pattern: never let a cache outage take down the request. +Build the handler defensively and fall back: + +```php +use InitPHP\Cache\Cache; +use InitPHP\Cache\Handler\Redis; +use InitPHP\Cache\Handler\File; +use InitPHP\Cache\Exception\CacheException; + +try { + $cache = Cache::create(Redis::class, ['host' => 'redis.internal']); + $cache->has('ping'); // force the lazy connection now, so we fail fast +} catch (CacheException $e) { + $cache = Cache::create(File::class, ['path' => sys_get_temp_dir() . '/cache']); +} +``` + +## Next steps + +- [Keys, TTL & Values](Keys-TTL-and-Values.md) — what makes a key invalid. +- [Troubleshooting](Troubleshooting.md) — symptoms, causes and fixes. +- [API Reference](API-Reference.md#exceptions) — the exception class definitions. diff --git a/docs/FAQ.md b/docs/FAQ.md new file mode 100644 index 0000000..da7cc78 --- /dev/null +++ b/docs/FAQ.md @@ -0,0 +1,95 @@ +# FAQ + +### Which handler should I use? + +- **Local development / small sites:** [File](File-Handler.md) — zero setup. +- **You already run a database, no extra service wanted:** [PDO](PDO-Handler.md). +- **Hot, shared cache across servers:** [Redis](Redis-Handler.md) or + [Memcache(d)](Memcache-Handler.md). +- **WinCache:** don't — it's [deprecated](WinCache-Handler.md), unmaintained, and has + no stable release for PHP 8. + +See the comparison table on the [Home](Home.md#the-handlers-at-a-glance) page. + +### Is this a PSR-16 cache? + +Yes. Every handler implements `Psr\SimpleCache\CacheInterface` (via +[`CacheInterface`](API-Reference.md#cacheinterface)), so you can use it anywhere a +PSR-16 cache is expected, and the package `provide`s +`psr/simple-cache-implementation`. + +### Can I store `null` / `false`? + +Yes — any serialisable value round-trips exactly. Because `get()` also returns +its default on a miss, use `has()` to tell a stored `null` from a miss. See +[Keys, TTL & Values](Keys-TTL-and-Values.md#null-values). + +### Why did my key throw an `InvalidArgumentException`? + +The key was empty or contained a PSR-16 reserved character (`{}()/\@:`). Common +culprits are `:` (e.g. `user:42`) and `/`. Use `.` or `_` instead, or hash +untrusted input. See [Keys, TTL & Values](Keys-TTL-and-Values.md#keys). + +### What does a TTL of `0` do? + +It **deletes** the item (it's already expired), and `set()` returns `true`. Use +`null` for "no expiry". See [TTL](Keys-TTL-and-Values.md#time-to-live-ttl). + +### Does `clear()` only remove my keys? + +It depends on the backend: + +- [File](File-Handler.md) and [PDO](PDO-Handler.md) clear only items with the handler's + `prefix`. +- [Redis](Redis-Handler.md) runs `FLUSHDB` (the whole selected database) and + [Memcache(d)](Memcache-Handler.md)/[WinCache](WinCache-Handler.md) flush the whole + store. + +For Redis, isolate with a dedicated `database`; for Memcached, a dedicated +instance. + +### Are `increment()` / `decrement()` atomic? + +No. They are uniform across handlers but implemented as read-modify-write, so +they can race under concurrency. For strict atomic counters, use the backend's +native command in its own keyspace. See [Counters](Counters.md#not-atomic-across-processes). + +### Does increment keep the item's TTL? + +No — `increment()`/`decrement()` store the new value **without** an expiry. If you +need a windowed counter, manage the TTL with `set()`. See the +[soft rate limiter](Counters.md#counters-and-ttl-a-soft-rate-limiter). + +### Can I change options after creating the handler? + +Yes: `setOptions(['key' => 'value'])` merges (case-insensitively) and returns the +handler. Read one back with `getOption('key', $default)`. See +[The Cache Factory](The-Cache-Factory.md#reading-and-changing-options-later). + +### The PDO handler — does it create the table? + +No. Create the table yourself with the schema for your database; the +[PDO Handler](PDO-Handler.md#create-the-table) page has ready-made `CREATE TABLE` +statements for MySQL, SQLite and PostgreSQL. + +### Does it work without Redis/Memcached extensions? + +The [File](File-Handler.md) handler needs nothing beyond PHP core, and +[PDO](PDO-Handler.md) needs only `ext-pdo`. The Redis and Memcache handlers need +their respective C extensions. Pre-check with `isSupported()` and fall back. See +[Installation](Installation.md#checking-a-handler-at-runtime). + +### How do I cache in tests without a server? + +Use a small in-memory handler (or the File handler with a temp dir). See +[Testing](Testing.md). + +### Can I add my own backend? + +Yes — extend [`BaseHandler`](API-Reference.md#basehandler) and implement six +methods. See [Custom Handlers](Custom-Handlers.md). + +## Still stuck? + +- [Troubleshooting](Troubleshooting.md) — symptoms and fixes. +- [Open an issue](https://github.com/InitPHP/Cache/issues/new). diff --git a/docs/File-Handler.md b/docs/File-Handler.md new file mode 100644 index 0000000..cf4a7a1 --- /dev/null +++ b/docs/File-Handler.md @@ -0,0 +1,102 @@ +# File Handler + +`InitPHP\Cache\Handler\File` stores each item as one PHP-serialised file named +`{prefix}{key}` inside a directory you choose. It needs **no extension** beyond +the PHP core, which makes it the simplest handler and a great default for local +development and small-to-medium caches. + +## Options + +| Option | Type | Default | Description | +| --- | --- | --- | --- | +| `prefix` | `string` | `cache_` | Prepended to keys; also the `clear()` filter. | +| `path` | `string` | _(required)_ | Directory the cache files live in. | +| `mode` | `int\|null` | `0640` | `chmod()` mode applied to each file. `null` skips `chmod()`. | + +## Usage + +```php +use InitPHP\Cache\Cache; +use InitPHP\Cache\Handler\File; + +$cache = Cache::create(File::class, [ + 'path' => __DIR__ . '/var/cache', + 'mode' => 0640, +]); + +$cache->set('settings', ['theme' => 'dark'], 3600); +$cache->get('settings'); // ['theme' => 'dark'] +``` + +The `path` directory must **exist and be writable** before you use the handler. +A quick bootstrap: + +```php +$dir = __DIR__ . '/var/cache'; +if (!is_dir($dir)) { + mkdir($dir, 0775, true); +} + +$cache = Cache::create(File::class, ['path' => $dir]); +``` + +If `path` is missing or empty, any operation that touches the filesystem throws a +[`CacheException`](Error-Handling.md). + +## How it works + +- Each item is `serialize()`d together with its creation time and TTL, then + written to `{path}/{prefix}{key}`. +- On read, an **expired file is deleted** and reported as a miss. +- A file that cannot be read or unserialised (corruption, a partial write) is + also treated as a miss rather than an error. +- `clear()` removes only files matching `{prefix}*`, and **never deletes** the + protective files `.htaccess`, `index.htm`, `index.html`, `index.php` or + `web.config`. + +```php +$cache->set('a', 1); +$cache->set('b', 2); +$cache->clear(); // removes app's "cache_a", "cache_b"; leaves index.php etc. +``` + +## Isolating caches with the prefix + +Two handlers pointed at the same directory but with different prefixes don't see +or clear each other's items: + +```php +$app = Cache::create(File::class, ['path' => $dir, 'prefix' => 'app_']); +$views = Cache::create(File::class, ['path' => $dir, 'prefix' => 'view_']); + +$app->set('x', 1); +$views->set('x', 2); + +$app->clear(); // only "app_*" files removed +$views->get('x'); // 2 — untouched +``` + +## Security notes + +- **Keep the cache directory out of the web root**, or protect it. The handler + preserves the protective files above so directories that can't be moved (e.g. + some shared hosts) can still be locked down with an `.htaccess` / `web.config`. +- Cache files are read with `unserialize()`. Point `path` only at a directory + **your application controls** — never at attacker-influenced content, since a + crafted file could instantiate objects on read. +- The default `mode` of `0640` keeps files readable only by the owner and group. + Tighten to `0600` if the web server is the sole user. + +## When to choose another handler + +- A single flat directory with **very many** files can slow the filesystem; + reach for [Redis](Redis-Handler.md) or [Memcache(d)](Memcache-Handler.md) for large, + hot caches. +- For a **shared cache across multiple servers**, use a networked backend; the + filesystem is per-host. + +## Next steps + +- [Configuration Options](Configuration-Options.md) — all handlers side by side. +- [Keys, TTL & Values](Keys-TTL-and-Values.md) — the rules for what you store. +- [Recipes](Recipes.md) — read-through, memoization, and more. diff --git a/docs/Home.md b/docs/Home.md new file mode 100644 index 0000000..5d40329 --- /dev/null +++ b/docs/Home.md @@ -0,0 +1,109 @@ +# InitPHP Cache — Wiki + +Welcome to the official documentation for **`initphp/cache`** — a small, +[PSR-16 (Simple Cache)](https://www.php-fig.org/psr/psr-16/) caching library for +**PHP 8.2+** with interchangeable handlers for the filesystem, PDO databases, +Redis, Memcache(d) and WinCache. + +```bash +composer require initphp/cache +``` + +```php +use InitPHP\Cache\Cache; +use InitPHP\Cache\Handler\File; + +$cache = Cache::create(File::class, ['path' => __DIR__ . '/var/cache']); + +$cache->set('user:42', ['name' => 'Jane'], 3600); // store for 1 hour +$cache->get('user:42'); // ['name' => 'Jane'] +$cache->get('missing', 'default'); // "default" +$cache->has('user:42'); // true +$cache->delete('user:42'); // true +``` + +One factory call picks the backend; the **API is identical for every handler**, +so you can develop against the [File](File-Handler.md) handler and switch to +[Redis](Redis-Handler.md) in production by changing a single line. + +## The package in one table + +| Symbol | Role | +| --- | --- | +| [`Cache`](The-Cache-Factory.md) | Static factory — builds and configures a handler. The usual entry point. | +| [`CacheInterface`](API-Reference.md#cacheinterface) | The contract every handler fulfils; extends `Psr\SimpleCache\CacheInterface`. | +| [`BaseHandler`](Custom-Handlers.md) | Abstract base with the shared behaviour; extend it to write your own handler. | +| [`Handler\File`](File-Handler.md) · [`Handler\PDO`](PDO-Handler.md) · [`Handler\Redis`](Redis-Handler.md) · [`Handler\Memcache`](Memcache-Handler.md) · [`Handler\Wincache`](WinCache-Handler.md) | The five built-in handlers. | +| [`CacheException`](Error-Handling.md) / [`InvalidArgumentException`](Error-Handling.md) | The two exception types; both implement the matching PSR-16 interface. | + +## Start here + +- **New to the package?** Read [Installation](Installation.md), then + [Quick Start](Quick-Start.md). +- **Choosing a backend?** Compare the [handlers](File-Handler.md) and their + [configuration options](Configuration-Options.md). +- **Want the precise rules** for keys, TTLs and values? + [Keys, TTL & Values](Keys-TTL-and-Values.md). +- **Building counters?** [Counters](Counters.md) explains `increment()` / + `decrement()`. +- **Looking for a specific method?** The full [API Reference](API-Reference.md) + lists every public member. +- **Writing your own backend?** [Custom Handlers](Custom-Handlers.md). + +## The handlers at a glance + +| Handler | Class | Backend | Needs | Best for | +| --- | --- | --- | --- | --- | +| [File](File-Handler.md) | `Handler\File` | Filesystem | core only | local dev, small/medium caches | +| [PDO](PDO-Handler.md) | `Handler\PDO` | SQL (MySQL, SQLite, PostgreSQL…) | `ext-pdo` | shared DB, no extra service | +| [Redis](Redis-Handler.md) | `Handler\Redis` | Redis | `ext-redis` | hot, distributed caches | +| [Memcache(d)](Memcache-Handler.md) | `Handler\Memcache` | Memcached | `ext-memcached` / `ext-memcache` | distributed, ephemeral caches | +| [WinCache](WinCache-Handler.md) | `Handler\Wincache` | WinCache user cache | `ext-wincache` | _deprecated — legacy Windows only_ | + +## What you get + +- **One PSR-16 API, five backends.** Every handler implements + [`CacheInterface`](API-Reference.md#cacheinterface), so your code never depends + on the concrete handler. +- **Exact value fidelity.** Anything `serialize()` accepts round-trips exactly — + including `null`, `false`, arrays and objects. See + [Keys, TTL & Values](Keys-TTL-and-Values.md). +- **Flexible TTLs.** `null` (forever), an integer of seconds, or a + `DateInterval`; a zero/negative TTL deletes the item. +- **Consistent counters.** `increment()` / `decrement()` behave identically on + every backend and return the new value. See [Counters](Counters.md). +- **Strict, predictable keys.** PSR-16 key validation with the reserved set + `{}()/\@:`. See [Keys, TTL & Values](Keys-TTL-and-Values.md). +- **PSR-16 exceptions.** Every error implements `Psr\SimpleCache\CacheException`, + so one `catch` covers the library. See [Error Handling](Error-Handling.md). +- **Extensible.** Add your own backend by extending + [`BaseHandler`](Custom-Handlers.md). + +## At a glance — behaviour + +| You call | You get | +| --- | --- | +| `set('k', $v)` | stores `$v` with no expiry → `true` | +| `set('k', $v, 60)` | stores `$v` for 60 seconds → `true` | +| `set('k', $v, new DateInterval('PT5M'))` | stores `$v` for 5 minutes → `true` | +| `set('k', $v, 0)` _(or negative)_ | deletes `k` → `true` | +| `get('missing')` | `null` | +| `get('missing', 'x')` | `"x"` (returned as-is, never invoked) | +| `get('k')` after storing `null` | `null` (use `has()` to detect the miss) | +| `increment('n', 5)` on a missing key | `5` (new value) | +| `get('bad:key')` | throws [`InvalidArgumentException`](Error-Handling.md) (`:` is reserved) | + +## Package metadata + +- **License**: MIT +- **Minimum PHP**: 8.2 +- **Runtime dependencies**: [`psr/simple-cache`](https://packagist.org/packages/psr/simple-cache) `^3.0` +- **Required extensions**: none for the [File](File-Handler.md) handler; one per backend otherwise +- **Packagist**: [`initphp/cache`](https://packagist.org/packages/initphp/cache) +- **Source**: [github.com/InitPHP/Cache](https://github.com/InitPHP/Cache) +- **Issues**: [github.com/InitPHP/Cache/issues](https://github.com/InitPHP/Cache/issues) +- **Discussions**: [github.com/orgs/InitPHP/discussions](https://github.com/orgs/InitPHP/discussions) + +If something in this wiki is unclear, wrong, or out of date, +[open an issue](https://github.com/InitPHP/Cache/issues/new) — documentation +fixes are merged eagerly. diff --git a/docs/Installation.md b/docs/Installation.md new file mode 100644 index 0000000..3f9701c --- /dev/null +++ b/docs/Installation.md @@ -0,0 +1,94 @@ +# Installation + +`initphp/cache` is distributed via +[Packagist](https://packagist.org/packages/initphp/cache). Its only runtime +dependency is the PSR-16 interface package; each backend may additionally need +its own PHP extension. + +## Requirements + +| Requirement | Notes | +| --- | --- | +| **PHP `>= 8.2`** | The code uses `declare(strict_types=1)`, `mixed`, and union types. | +| [`psr/simple-cache`](https://packagist.org/packages/psr/simple-cache) `^3.0` | Pulled in automatically by Composer. | +| Composer | For installation and autoloading. | + +### Per-handler extensions + +| Handler | Extension | +| --- | --- | +| [File](File-Handler.md) | none — PHP core only | +| [PDO](PDO-Handler.md) | `ext-pdo` (plus the matching driver, e.g. `pdo_mysql`, `pdo_sqlite`) | +| [Redis](Redis-Handler.md) | `ext-redis` (phpredis) | +| [Memcache(d)](Memcache-Handler.md) | `ext-memcached` (preferred) or `ext-memcache` | +| [WinCache](WinCache-Handler.md) | `ext-wincache` — _deprecated, Windows only_ | + +> You only need the extension for the handler you actually use. The File handler +> works on any supported PHP install with no extra setup. + +## Install + +```bash +composer require initphp/cache +``` + +Composer registers the PSR-4 namespace `InitPHP\Cache\`, so everything is +available as soon as you require `vendor/autoload.php`. + +## Verify the install + +Drop this script into your project root as `check-cache.php`: + +```php + $dir]); + +$cache->set('check', 'it works', 60); + +echo $cache->get('check') === 'it works' + ? "InitPHP Cache is working.\n" + : "Something is wrong.\n"; + +$cache->delete('check'); +``` + +```bash +php check-cache.php +# InitPHP Cache is working. +``` + +## Checking a handler at runtime + +Every handler can tell you whether the current runtime supports it +(`isSupported()`), which is handy for picking a backend dynamically: + +```php +use InitPHP\Cache\Handler\Redis; +use InitPHP\Cache\Handler\File; +use InitPHP\Cache\Cache; + +$cache = (new Redis())->isSupported() + ? Cache::create(Redis::class, ['host' => '127.0.0.1']) + : Cache::create(File::class, ['path' => __DIR__ . '/var/cache']); +``` + +> Building an unsupported handler through the factory (e.g. `Redis` without +> `ext-redis`) throws a [`CacheException`](Error-Handling.md). The check above lets +> you fall back gracefully instead. + +## Next steps + +- [Quick Start](Quick-Start.md) — store and read your first values. +- [The Cache Factory](The-Cache-Factory.md) — everything `Cache::create()` does. +- [Configuration Options](Configuration-Options.md) — every option of every handler. diff --git a/docs/Keys-TTL-and-Values.md b/docs/Keys-TTL-and-Values.md new file mode 100644 index 0000000..aa7bc81 --- /dev/null +++ b/docs/Keys-TTL-and-Values.md @@ -0,0 +1,153 @@ +# Keys, TTL & Values + +This page covers the three things you control on every write: the **key**, the +**value**, and the **time-to-live**. The rules are the same for every handler. + +## Keys + +A cache key must be a **non-empty string** that contains **none** of the +characters reserved by PSR-16: + +``` +{ } ( ) / \ @ : +``` + +Break either rule and the library throws an +[`InvalidArgumentException`](Error-Handling.md): + +```php +$cache->get('user.42'); // fine +$cache->get('user_42'); // fine +$cache->get('user:42'); // throws — ":" is reserved +$cache->get(''); // throws — empty key +``` + +The reserved set is available as a constant: + +```php +InitPHP\Cache\BaseHandler::RESERVED_CHARACTERS; // "{}()/\@:" +``` + +> **Why `/` and `\` are reserved matters for the File handler:** because they can +> never appear in a key, a key can never escape the cache directory. Keys are +> safe to build from user-controlled identifiers — but see +> [practical key advice](#practical-key-advice) below. + +### The prefix + +Every key is automatically prefixed with the `prefix` option (default `cache_`) +**after** validation, so the prefix itself is not subject to the reserved-char +rule. The prefix: + +- keeps two applications that share one backend from reading each other's keys; +- scopes `clear()` — only items with the handler's prefix are removed (for the + [File](File-Handler.md) and [PDO](PDO-Handler.md) handlers). + +```php +$cache = Cache::create(File::class, ['path' => $dir, 'prefix' => 'app_']); +$cache->set('user', $u); // physically stored as "app_user" +``` + +Set `prefix` to `''` to disable it. + +### Practical key advice + +- Keep keys reasonably short and ASCII. The [File](File-Handler.md) handler uses the + prefixed key as a filename, so extremely long keys can hit filesystem limits. +- A common trick for arbitrary input is to hash it into a safe key: + ```php + $key = 'page_' . hash('xxh3', $url); // no reserved chars, bounded length + $cache->set($key, $html, 600); + ``` + +## Values + +Any value PHP's `serialize()` can handle round-trips **exactly**: strings, +integers, floats, booleans, `null`, arrays and objects. + +```php +$cache->set('int', 42); $cache->get('int'); // 42 (int) +$cache->set('float', 3.14); $cache->get('float'); // 3.14 (float) +$cache->set('bool', false); $cache->get('bool'); // false (bool) +$cache->set('list', [1, 2, 3]); $cache->get('list'); // [1,2,3] (array) + +$user = new stdClass(); +$user->name = 'Jane'; +$cache->set('user', $user); +$cache->get('user'); // stdClass { name: "Jane" } +``` + +> Objects must be serialisable. Closures, PDO connections, open resources and the +> like cannot be cached. + +### `null` values + +`null` is a perfectly valid value — it is stored and returned as `null`, not +treated as "absent": + +```php +$cache->set('maybe', null); +$cache->has('maybe'); // true — it really is stored +$cache->get('maybe', 'default'); // null — NOT "default" +``` + +Because `get()` also returns its `$default` on a miss, you cannot tell a stored +`null` from a miss using `get()` alone. Use `has()` when that distinction +matters: + +```php +if (!$cache->has('maybe')) { + $cache->set('maybe', compute()); // only compute on a real miss +} +$value = $cache->get('maybe'); +``` + +### The default is returned as-is + +`get($key, $default)` returns `$default` verbatim on a miss. It is **never +called**, even if it is a callable — this matches PSR-16: + +```php +$cache->get('missing', 'strlen'); // "strlen" (the string), not a function call +``` + +If you want lazy computation, use the `has()`/`get()` pattern above. + +## Time-to-live (TTL) + +`set()` and `setMultiple()` accept the TTL as the last argument. It can be `null`, +an integer number of seconds, or a `DateInterval`: + +| TTL value | Effect | +| --- | --- | +| `null` (default) | Store with **no expiry** — kept until deleted or evicted. | +| positive `int` | Expire after that many **seconds**. | +| `DateInterval` | Expire after the interval, measured from **now**. | +| `0` or negative `int` | **Delete** the item; `set()` returns `true`. | + +```php +$cache->set('a', 1); // forever +$cache->set('b', 1, 60); // 60 seconds +$cache->set('c', 1, new DateInterval('PT5M')); // 5 minutes +$cache->set('d', 1, 0); // deletes "d", returns true +$cache->set('e', 1, -10); // same — already expired +``` + +### Where expiry is enforced + +- The [File](File-Handler.md) and [PDO](PDO-Handler.md) handlers store the expiry + alongside the value and drop the item on read once it has passed. +- The [Redis](Redis-Handler.md), [Memcache(d)](Memcache-Handler.md) and + [WinCache](WinCache-Handler.md) handlers delegate expiry to the backend. + +In all cases the observable behaviour is identical: an expired item reads back as +a miss. + +> The Memcache and WinCache handlers also have a `default_ttl` option used **only +> when `set()` is called without a TTL** (`0` = no expiry). See their pages. + +## Next steps + +- [Counters](Counters.md) — `increment()` / `decrement()` semantics. +- [Bulk Operations](Bulk-Operations.md) — many keys at once. +- [Error Handling](Error-Handling.md) — what gets thrown, and when. diff --git a/docs/Memcache-Handler.md b/docs/Memcache-Handler.md new file mode 100644 index 0000000..2d74296 --- /dev/null +++ b/docs/Memcache-Handler.md @@ -0,0 +1,91 @@ +# Memcache(d) Handler + +`InitPHP\Cache\Handler\Memcache` stores items in Memcached. It works with either +the modern [`Memcached`](https://www.php.net/manual/en/book.memcached.php) +extension (**preferred**) or the legacy `Memcache` extension; if both are +installed, `Memcached` is used. + +## Options + +| Option | Type | Default | Description | +| --- | --- | --- | --- | +| `prefix` | `string` | `cache_` | Prepended to keys. | +| `host` | `string` | `127.0.0.1` | Server host. | +| `port` | `int` | `11211` | Server port. | +| `weight` | `int` | `1` | Server weight (Memcached only). | +| `default_ttl` | `int` | `0` | Expiry used when `set()` is called **without** a TTL. `0` = no expiry. | + +## Usage + +```php +use InitPHP\Cache\Cache; +use InitPHP\Cache\Handler\Memcache; + +$cache = Cache::create(Memcache::class, [ + 'host' => '127.0.0.1', + 'port' => 11211, +]); + +$cache->set('fragment:nav', $html, 600); +$cache->get('fragment:nav'); +``` + +## How it works + +- Each value is stored as a small **serialised envelope**, so `null`, `false`, + arrays and objects round-trip exactly. +- TTLs are delegated to the server. When `set()` is called **without** a TTL, the + `default_ttl` option is applied (`0` means "no expiry"). +- `has()` reports whether the key returns a stored value. +- `clear()` calls **`flush()`**, which clears the **entire Memcached instance** — + it is **not** limited by `prefix`. + +```php +$cache->set('a', 1); // explicit no-TTL → uses default_ttl (0 = forever) +$cache->set('b', 2, 60); // 60-second TTL +$cache->clear(); // flushes the whole server, not just "cache_*" +``` + +> **`clear()` is global.** Because Memcached has no key enumeration, `flush()` +> wipes everything on the server, including keys written by other apps that share +> it. Run a dedicated Memcached instance for a cache you intend to `clear()`. + +## The `default_ttl` option + +`default_ttl` only matters for `set()` calls that omit the TTL argument. An +explicit TTL always wins, and an explicit `0`/negative still deletes the item: + +```php +$cache = Cache::create(Memcache::class, ['default_ttl' => 300]); + +$cache->set('a', 1); // no TTL given → expires in 300s (default_ttl) +$cache->set('b', 2, 60); // explicit → 60s +$cache->set('c', 3, 0); // explicit 0 → deletes "c" +``` + +## Connection and requirements + +The handler connects on first use and throws a +[`CacheException`](Error-Handling.md) when neither extension is available or the +server cannot be reached: + +```php +extension_loaded('memcached') || extension_loaded('memcache'); // true when usable +``` + +```php +use InitPHP\Cache\Exception\CacheException; + +try { + $cache = Cache::create(Memcache::class, ['host' => 'memcached.internal']); + $cache->set('k', 'v'); +} catch (CacheException $e) { + error_log('Memcached unavailable: ' . $e->getMessage()); +} +``` + +## Next steps + +- [Configuration Options](Configuration-Options.md) — all handlers side by side. +- [Keys, TTL & Values](Keys-TTL-and-Values.md) — `default_ttl` vs an explicit TTL. +- [Error Handling](Error-Handling.md) — connection failures and exceptions. diff --git a/docs/PDO-Handler.md b/docs/PDO-Handler.md new file mode 100644 index 0000000..aa4d4f1 --- /dev/null +++ b/docs/PDO-Handler.md @@ -0,0 +1,130 @@ +# PDO Handler + +`InitPHP\Cache\Handler\PDO` stores items in a single database table through PDO. +It is **portable** across MySQL, SQLite and PostgreSQL: MySQL-specific tuning runs +only on MySQL, and everything else is plain ANSI SQL. Requires `ext-pdo` plus the +driver for your database (`pdo_mysql`, `pdo_sqlite`, `pdo_pgsql`…). + +## Options + +| Option | Type | Default | Description | +| --- | --- | --- | --- | +| `prefix` | `string` | `cache_` | Prepended to keys; also the `clear()` filter. | +| `dsn` | `string` | `mysql:host=localhost;dbname=test` | PDO connection DSN. | +| `username` | `string\|null` | `null` | Connection user. | +| `password` | `string\|null` | `null` | Connection password. | +| `charset` | `string` | `utf8mb4` | **MySQL only** (`SET NAMES`). | +| `collation` | `string` | `utf8mb4_general_ci` | **MySQL only**. | +| `table` | `string` | `cache` | Table name; must match `[A-Za-z0-9_]+`. | + +## Create the table + +The table needs a **unique** `name` column, a nullable integer `ttl` (the +absolute expiry timestamp) and a text `data` column. + +**MySQL** + +```sql +CREATE TABLE `cache` ( + `name` VARCHAR(255) NOT NULL, + `ttl` INT NULL DEFAULT NULL, + `data` TEXT NOT NULL, + UNIQUE (`name`) +) ENGINE = InnoDB CHARSET = utf8mb4 COLLATE = utf8mb4_general_ci; +``` + +**SQLite** + +```sql +CREATE TABLE cache ( + name VARCHAR(255) NOT NULL, + ttl INTEGER NULL DEFAULT NULL, + data TEXT NOT NULL, + UNIQUE (name) +); +``` + +**PostgreSQL** + +```sql +CREATE TABLE cache ( + name VARCHAR(255) NOT NULL UNIQUE, + ttl INTEGER NULL, + data TEXT NOT NULL +); +``` + +## Usage + +```php +use InitPHP\Cache\Cache; +use InitPHP\Cache\Handler\PDO; + +$cache = Cache::create(PDO::class, [ + 'dsn' => 'mysql:host=127.0.0.1;dbname=app', + 'username' => 'app', + 'password' => 'secret', + 'table' => 'cache', +]); + +$cache->set('feed', $items, 300); +$cache->get('feed'); +``` + +SQLite — a file or an in-memory database — works the same way: + +```php +$cache = Cache::create(PDO::class, [ + 'dsn' => 'sqlite:' . __DIR__ . '/var/cache.sqlite', +]); +``` + +## How it works + +- `set()` **upserts** (a `DELETE` + `INSERT` wrapped in a transaction), so + writing the same key twice overwrites it cleanly. +- `ttl` is stored as an **absolute expiry timestamp**; an expired row is deleted + on read and reported as a miss. +- `clear()` deletes rows whose `name` matches the prefix, **escaping `LIKE` + wildcards** so a prefix such as `cache_` is matched literally (the `_` is not + treated as a single-character wildcard). +- On MySQL the connection runs `SET NAMES … COLLATE …` from the `charset` / + `collation` options; on other drivers those options are ignored. + +## Errors + +| Situation | Result | +| --- | --- | +| Connection cannot be established | throws [`CacheException`](Error-Handling.md) | +| `table` option contains anything but `[A-Za-z0-9_]` | throws `CacheException` | +| A query fails at runtime (e.g. the table is missing) | the call returns `false` / a miss — it does **not** throw | + +```php +use InitPHP\Cache\Exception\CacheException; + +try { + $cache = Cache::create(PDO::class, ['dsn' => 'mysql:host=db;dbname=app']); + $cache->get('x'); +} catch (CacheException $e) { + error_log('Cache DB unavailable: ' . $e->getMessage()); + // fall back to another handler, or proceed without caching +} +``` + +> The `table` name is validated (not parameterisable in SQL), so keep it a plain +> identifier. Everything that can be parameterised (keys, values, TTLs) uses +> prepared statements. + +## When to choose another handler + +- The PDO handler reuses an existing database — no extra service to run — which + is its main appeal. For the **hottest** caches a dedicated in-memory store like + [Redis](Redis-Handler.md) will usually be faster. +- Heavy cache churn adds write load to your database; size the table's storage + and cleanup accordingly (expired rows are removed lazily, on read). + +## Next steps + +- [Configuration Options](Configuration-Options.md) — all handlers side by side. +- [Error Handling](Error-Handling.md) — what throws, what returns `false`. +- [Recipes](Recipes.md) — practical caching patterns. diff --git a/docs/Quick-Start.md b/docs/Quick-Start.md new file mode 100644 index 0000000..7a048be --- /dev/null +++ b/docs/Quick-Start.md @@ -0,0 +1,132 @@ +# Quick Start + +Five minutes from `composer require` to a working cache. + +## 1. Build a handler + +Use the [`Cache::create()`](The-Cache-Factory.md) factory. Its first argument is a +handler class; the second is an options array. + +```php + __DIR__ . '/var/cache', // the directory must exist and be writable +]); +``` + +`create()` returns an object implementing +[`CacheInterface`](API-Reference.md#cacheinterface), which extends +`Psr\SimpleCache\CacheInterface`. You can type-hint either interface anywhere in +your app. + +## 2. Store and read + +```php +$cache->set('greeting', 'Hello'); // no TTL → kept until deleted +$cache->set('token', 'abc123', 3600); // expires in 3600 seconds + +$cache->get('greeting'); // "Hello" +$cache->get('unknown'); // null (default) +$cache->get('unknown', 'fallback'); // "fallback" + +$cache->has('greeting'); // true +$cache->delete('greeting'); // true +$cache->clear(); // wipe everything this handler owns +``` + +Values keep their type and structure — strings, ints, floats, booleans, `null`, +arrays and objects all round-trip exactly: + +```php +$cache->set('config', ['debug' => true, 'level' => 5]); +$cache->get('config'); // ['debug' => true, 'level' => 5] +``` + +## 3. The read-through pattern + +The most common use of a cache: return the stored value, or compute and store it +on a miss. + +```php +$report = $cache->get('daily-report'); + +if ($report === null) { + $report = build_expensive_report(); // your slow code + $cache->set('daily-report', $report, 86400); // cache for a day +} + +return $report; +``` + +> If `null` is a legitimate value for you, use `has()` to tell a miss from a +> stored `null` — see [Keys, TTL & Values](Keys-TTL-and-Values.md#null-values). + +## 4. Switch the backend in one line + +Because every handler shares the same API, moving from the filesystem to Redis is +a one-line change: + +```php +use InitPHP\Cache\Handler\Redis; + +$cache = Cache::create(Redis::class, [ + 'host' => '127.0.0.1', + 'port' => 6379, + 'database' => 0, +]); + +// ...the rest of your code is unchanged. +$cache->set('user:42', ['name' => 'Jane'], 3600); +``` + +See the [handler pages](File-Handler.md) for each backend's options. + +## 5. Bulk operations and counters + +```php +// Many at once (accepts arrays or any iterable) +$cache->setMultiple(['a' => 1, 'b' => 2, 'c' => 3], 600); +$cache->getMultiple(['a', 'b', 'missing'], 0); // ['a'=>1, 'b'=>2, 'missing'=>0] +$cache->deleteMultiple(['a', 'b']); + +// Counters (return the new value; not atomic) +$cache->increment('views'); // 1 +$cache->increment('views', 5); // 6 +$cache->decrement('views', 2); // 4 +``` + +See [Bulk Operations](Bulk-Operations.md) and [Counters](Counters.md). + +## What just happened + +1. `create()` instantiated the handler, verified the runtime supports it, and + merged your options over the defaults. +2. `set()` serialised the value and wrote it to the backend, with the TTL you + gave (or none). +3. `get()` read it back, returned your `$default` on a miss, and honoured the + expiry. + +## Things worth knowing immediately + +- **Keys are validated.** A key must be a non-empty string with none of the + reserved characters `{}()/\@:`; otherwise an + [`InvalidArgumentException`](Error-Handling.md) is thrown. See + [Keys, TTL & Values](Keys-TTL-and-Values.md#keys). +- **A zero or negative TTL deletes the item** (and returns `true`). +- **The default key prefix is `cache_`.** It scopes `clear()` so caches sharing + one backend don't wipe each other. Change it with the `prefix` option. +- **`get()` never calls your default.** A callable default is returned as a plain + value, per PSR-16. + +## Next steps + +- [The Cache Factory](The-Cache-Factory.md) — instances, options, error cases. +- [Keys, TTL & Values](Keys-TTL-and-Values.md) — the full rules. +- [Recipes](Recipes.md) — read-through, memoization, rate limiting, and more. +- [Configuration Options](Configuration-Options.md) — every option, every handler. diff --git a/docs/README.md b/docs/README.md deleted file mode 100644 index dfee462..0000000 --- a/docs/README.md +++ /dev/null @@ -1,39 +0,0 @@ -# InitPHP Cache — Documentation - -`initphp/cache` is a [PSR-16](https://www.php-fig.org/psr/psr-16/) cache library -with interchangeable handlers. You configure a handler once through the -`Cache::create()` factory and then use the standard PSR-16 API everywhere. - -## Contents - -1. [Getting started](getting-started.md) — install, the factory, the read-through - pattern. -2. [Configuration & options](configuration.md) — every option of every handler. -3. [PSR-16 behaviour & the handler API](psr-16.md) — keys, TTLs, bulk methods and - the counter contract. -4. Handlers - - [File](file-handler.md) - - [PDO](pdo-handler.md) - - [Redis](redis-handler.md) - - [Memcache(d)](memcache-handler.md) - - [WinCache](wincache-handler.md) -5. [Exceptions](exceptions.md) - -## The 30-second version - -```php -use InitPHP\Cache\Cache; -use InitPHP\Cache\Handler\File; - -$cache = Cache::create(File::class, ['path' => __DIR__ . '/var/cache']); - -$cache->set('key', 'value', 300); // store for 5 minutes -$cache->get('key'); // "value" -$cache->get('missing', 'default');// "default" -$cache->has('key'); // true -$cache->delete('key'); // true -``` - -Every handler implements `InitPHP\Cache\CacheInterface`, which extends -`Psr\SimpleCache\CacheInterface`. Code that depends on the PSR interface works -with any handler unchanged. diff --git a/docs/Recipes.md b/docs/Recipes.md new file mode 100644 index 0000000..67d4f73 --- /dev/null +++ b/docs/Recipes.md @@ -0,0 +1,164 @@ +# Recipes + +Practical patterns built on the plain PSR-16 API. They work with **any** +[handler](File-Handler.md). + +## A reusable `remember()` helper + +The cache-aside / read-through pattern, factored into one helper. It uses +`has()` so a producer that legitimately returns `null` is still cached: + +```php +use InitPHP\Cache\CacheInterface; + +function remember(CacheInterface $cache, string $key, int $ttl, callable $producer): mixed +{ + if ($cache->has($key)) { + return $cache->get($key); + } + $value = $producer(); + $cache->set($key, $value, $ttl); + return $value; +} +``` + +```php +$settings = remember($cache, 'settings', 3600, function () use ($db) { + return $db->query('SELECT * FROM settings')->fetchAll(); +}); +``` + +## Memoize an expensive computation + +```php +$key = 'fib_' . $n; + +$result = remember($cache, $key, 86400, fn () => fibonacci($n)); +``` + +## Cache a database query + +Build the key from whatever makes the query unique, and hash it to stay within +the [key rules](Keys-TTL-and-Values.md#keys): + +```php +function cachedQuery(CacheInterface $cache, PDO $db, string $sql, array $params, int $ttl = 300): array +{ + $key = 'q_' . hash('xxh3', $sql . '|' . serialize($params)); + + return remember($cache, $key, $ttl, function () use ($db, $sql, $params) { + $stmt = $db->prepare($sql); + $stmt->execute($params); + return $stmt->fetchAll(PDO::FETCH_ASSOC); + }); +} +``` + +```php +$active = cachedQuery($cache, $db, 'SELECT * FROM users WHERE status = ?', ['active']); +``` + +Remember to **invalidate** when the underlying data changes: + +```php +function updateUserStatus(CacheInterface $cache, PDO $db, int $id, string $status): void +{ + $db->prepare('UPDATE users SET status = ? WHERE id = ?')->execute([$status, $id]); + $cache->delete('q_' . hash('xxh3', 'SELECT * FROM users WHERE status = ?|' . serialize(['active']))); +} +``` + +> Cache invalidation is the hard part. Keep keys derivable so you can delete the +> exact entries you wrote, or use short TTLs and accept brief staleness. + +## Cache an HTTP/API response + +```php +function fetchJson(CacheInterface $cache, string $url, int $ttl = 600): array +{ + return remember($cache, 'http_' . hash('xxh3', $url), $ttl, function () use ($url) { + return json_decode(file_get_contents($url), true); + }); +} +``` + +## Fragment caching (rendered HTML) + +```php +function renderNav(CacheInterface $cache, callable $render): string +{ + return remember($cache, 'frag_nav', 600, $render); +} + +echo renderNav($cache, fn () => view('partials/nav', ['user' => $user])); +``` + +## Pick a backend per environment + +Develop on the filesystem, run Redis in production — one place decides: + +```php +use InitPHP\Cache\Cache; +use InitPHP\Cache\Handler\File; +use InitPHP\Cache\Handler\Redis; + +function makeCache(string $env): \InitPHP\Cache\CacheInterface +{ + return match ($env) { + 'production', 'staging' => Cache::create(Redis::class, [ + 'host' => getenv('REDIS_HOST') ?: '127.0.0.1', + 'database' => 1, + 'prefix' => 'app_', + ]), + default => Cache::create(File::class, [ + 'path' => __DIR__ . '/var/cache', + 'prefix' => 'app_', + ]), + }; +} + +$cache = makeCache(getenv('APP_ENV') ?: 'local'); +``` + +## Share one instance via a container + +A cache is cheap to build but you usually want a **single** configured instance. +Register it once and inject the `CacheInterface`: + +```php +// Pseudo-container registration +$container->singleton(CacheInterface::class, fn () => makeCache(getenv('APP_ENV'))); + +// Anywhere else — depend on the interface, not the handler +final class ReportService +{ + public function __construct(private CacheInterface $cache) {} + + public function daily(): array + { + return remember($this->cache, 'daily_report', 86400, fn () => $this->build()); + } +} +``` + +## A note on cache stampede + +When a popular key expires, many concurrent requests can recompute it at once. +Simple mitigations: + +- **Jitter the TTL** so keys don't all expire together: + ```php + $cache->set($key, $value, 3600 + random_int(0, 300)); + ``` +- **Refresh slightly early** by storing your own "soft expiry" timestamp inside + the value and recomputing in one request when it's near. +- For strict single-flight, guard the recompute with a short-lived lock key + (`set('lock_'.$key, 1, 5)` and only the winner rebuilds). + +For most apps, jittered TTLs are enough. + +## Next steps + +- [Counters](Counters.md) — view counters and soft rate limits. +- [Testing](Testing.md) — test code that depends on a cache. +- [Error Handling](Error-Handling.md) — degrade gracefully when a backend is down. diff --git a/docs/Redis-Handler.md b/docs/Redis-Handler.md new file mode 100644 index 0000000..58b0fc3 --- /dev/null +++ b/docs/Redis-Handler.md @@ -0,0 +1,94 @@ +# Redis Handler + +`InitPHP\Cache\Handler\Redis` stores items in Redis through the +[phpredis](https://github.com/phpredis/phpredis) extension (`ext-redis`). It is a +good choice for hot, distributed caches shared across many servers. + +## Options + +| Option | Type | Default | Description | +| --- | --- | --- | --- | +| `prefix` | `string` | `cache_` | Prepended to keys. | +| `host` | `string` | `127.0.0.1` | Server host. | +| `port` | `int` | `6379` | Server port. | +| `timeout` | `int\|float` | `0` | Connection timeout in seconds (`0` = unlimited). | +| `password` | `string\|null` | `null` | `AUTH` password; skipped when `null`. | +| `database` | `int\|null` | `0` | Database index to `SELECT`. | + +## Usage + +```php +use InitPHP\Cache\Cache; +use InitPHP\Cache\Handler\Redis; + +$cache = Cache::create(Redis::class, [ + 'host' => '127.0.0.1', + 'port' => 6379, + 'database' => 1, + 'password' => null, +]); + +$cache->set('session:abc', $payload, 1800); +$cache->get('session:abc'); +``` + +## How it works + +- Each value is stored as a small **serialised envelope**, so `null`, `false`, + arrays and objects round-trip exactly (a bare Redis string could not tell a + stored `false` from a miss — the envelope fixes that). +- TTLs are delegated to Redis with `SETEX`; an item with no TTL never expires. +- `has()` uses `EXISTS`. +- `clear()` runs **`FLUSHDB`**, which clears the **whole selected database**, + regardless of `prefix`. + +> **Isolate with `database`, not just `prefix`.** Because `clear()` flushes the +> entire database, point the handler at a dedicated database index if other data +> shares the server: +> +> ```php +> $cache = Cache::create(Redis::class, ['database' => 3]); +> $cache->clear(); // flushes only database 3 +> ``` + +## Connection lifecycle + +The connection is opened lazily on first use and reused for the handler's +lifetime. A failed **connection**, **authentication** (`AUTH`) or **database +selection** (`SELECT`) throws a [`CacheException`](Error-Handling.md) that wraps the +underlying `RedisException`: + +```php +use InitPHP\Cache\Exception\CacheException; + +try { + $cache = Cache::create(Redis::class, ['host' => 'redis.internal']); + $cache->set('k', 'v'); +} catch (CacheException $e) { + error_log('Redis unavailable: ' . $e->getMessage()); +} +``` + +## Requirements + +This handler needs the **phpredis C extension** (`ext-redis`). Check it with: + +```php +extension_loaded('redis'); // true when available +``` + +If you cannot install the extension, use a PSR-16 adapter over a pure-PHP client +(such as Predis), or fall back to the [PDO](PDO-Handler.md) or [File](File-Handler.md) +handler. + +## Atomic counters + +This library's [`increment()` / `decrement()`](Counters.md) are uniform across +handlers and therefore **not** atomic. For a strict atomic Redis counter, call +phpredis directly in its own keyspace — see [Counters](Counters.md#not-atomic-across-processes). + +## Next steps + +- [Configuration Options](Configuration-Options.md) — all handlers side by side. +- [Counters](Counters.md) — the counter contract and the atomic alternative. +- [Error Handling](Error-Handling.md) — connection failures and exceptions. diff --git a/docs/Testing.md b/docs/Testing.md new file mode 100644 index 0000000..acd59a1 --- /dev/null +++ b/docs/Testing.md @@ -0,0 +1,142 @@ +# Testing + +When your code depends on a cache, you want tests that are **fast**, +**isolated** and **don't need a running Redis/Memcached**. Because everything is +behind [`CacheInterface`](API-Reference.md#cacheinterface), that's easy. + +## Depend on the interface + +Inject `CacheInterface`, never a concrete handler. Production wires a real +backend; tests pass a lightweight one. + +```php +use InitPHP\Cache\CacheInterface; + +final class PriceService +{ + public function __construct(private CacheInterface $cache) {} + + public function priceFor(string $sku): int + { + if ($this->cache->has("price_$sku")) { + return $this->cache->get("price_$sku"); + } + $price = $this->lookupExpensive($sku); + $this->cache->set("price_$sku", $price, 60); + return $price; + } + + private function lookupExpensive(string $sku): int { /* ... */ } +} +``` + +## Option 1 — an in-memory handler (recommended) + +Drop the dependency-free `ArrayHandler` from [Custom Handlers](Custom-Handlers.md) +into your test suite and use it directly. It is real (it goes through +[`BaseHandler`](API-Reference.md#basehandler), so keys, TTLs and counters behave +exactly as in production) but holds everything in a PHP array. + +```php +use PHPUnit\Framework\TestCase; +use App\Cache\ArrayHandler; // see the "Custom Handlers" page + +final class PriceServiceTest extends TestCase +{ + public function testCachesTheLookup(): void + { + $cache = new ArrayHandler(); + $service = new PriceService($cache); + + $first = $service->priceFor('ABC'); + $second = $service->priceFor('ABC'); + + self::assertSame($first, $second); + self::assertTrue($cache->has('cache_price_ABC')); // prefix is applied + } +} +``` + +> The stored key is `cache_price_ABC` because the default `prefix` is `cache_`. +> Set `['prefix' => '']` on the handler if you'd rather assert on raw keys. + +## Option 2 — the File handler in a temp directory + +If you'd rather exercise a real backend end-to-end without extra services, point +the [File handler](File-Handler.md) at a throwaway directory: + +```php +use PHPUnit\Framework\TestCase; +use InitPHP\Cache\Cache; +use InitPHP\Cache\Handler\File; +use InitPHP\Cache\CacheInterface; + +final class PriceServiceFileTest extends TestCase +{ + private string $dir; + private CacheInterface $cache; + + protected function setUp(): void + { + $this->dir = sys_get_temp_dir() . '/cache-test-' . uniqid(); + mkdir($this->dir); + $this->cache = Cache::create(File::class, ['path' => $this->dir]); + } + + protected function tearDown(): void + { + array_map('unlink', glob($this->dir . '/*') ?: []); + @rmdir($this->dir); + } + + public function testRoundTrip(): void + { + $this->cache->set('k', 'v'); + self::assertSame('v', $this->cache->get('k')); + } +} +``` + +## Option 3 — a mock + +When you only need to assert that the cache was *used*, a mock from your test +framework is enough: + +```php +$cache = $this->createMock(\InitPHP\Cache\CacheInterface::class); +$cache->expects($this->once())->method('set')->with('price_ABC', 42, 60); +$cache->method('has')->willReturn(false); + +(new PriceService($cache))->priceFor('ABC'); +``` + +Prefer the in-memory handler for behaviour tests (it actually stores and +expires); reach for a mock only to assert specific interactions. + +## Testing expiry without `sleep()` + +Real-time expiry is awkward to test. Two reliable approaches: + +- Assert the **zero/negative-TTL = delete** behaviour, which is instant: + ```php + $cache->set('k', 'v'); + $cache->set('k', 'v', 0); // deletes + self::assertFalse($cache->has('k')); + ``` +- For the File handler, write the underlying file with a past timestamp to force + expiry deterministically (this is exactly how the package tests its own File + handler). + +## How the package itself is tested + +`initphp/cache` runs one shared **contract test** against an in-memory handler, +the File handler and the PDO handler (over SQLite), plus a **Redis/Memcached +integration** suite gated behind a `@group integration` marker so the default run +needs no services. It's a good model: test your glue against an in-memory handler +by default, and run the real backend only where it adds value. + +## Next steps + +- [Custom Handlers](Custom-Handlers.md) — the `ArrayHandler` used above. +- [Counters](Counters.md) / [Keys, TTL & Values](Keys-TTL-and-Values.md) — the exact + behaviour your tests can rely on. diff --git a/docs/The-Cache-Factory.md b/docs/The-Cache-Factory.md new file mode 100644 index 0000000..ee37473 --- /dev/null +++ b/docs/The-Cache-Factory.md @@ -0,0 +1,129 @@ +# The Cache Factory + +`InitPHP\Cache\Cache` is a tiny factory with a single static method. It builds a +handler, checks the runtime supports it, applies your options, and hands you back +a [`CacheInterface`](API-Reference.md#cacheinterface). + +```php +namespace InitPHP\Cache; + +final class Cache +{ + public static function create( + string|CacheInterface $handler, + array $options = [] + ): CacheInterface; +} +``` + +## Create from a class name + +The usual form — pass a handler class and its options: + +```php +use InitPHP\Cache\Cache; +use InitPHP\Cache\Handler\File; + +$cache = Cache::create(File::class, [ + 'path' => __DIR__ . '/var/cache', + 'prefix' => 'app_', +]); +``` + +The class is instantiated for you, so it must be one of the built-in handlers or +your own class that implements [`CacheInterface`](API-Reference.md#cacheinterface) +and has a no-argument-compatible constructor (extending +[`BaseHandler`](Custom-Handlers.md) gives you exactly that). + +## Create from an instance + +If you have already built a handler, pass it straight through. `create()` simply +applies the options and returns it: + +```php +$handler = new File(['path' => __DIR__ . '/var/cache']); + +$cache = Cache::create($handler, ['prefix' => 'app_']); +// $cache === $handler +``` + +## You don't have to use the factory + +The factory is convenience, not ceremony. Every handler's constructor accepts the +same options array, so this is equivalent to the first example: + +```php +use InitPHP\Cache\Handler\File; + +$cache = new File([ + 'path' => __DIR__ . '/var/cache', + 'prefix' => 'app_', +]); +``` + +The factory earns its keep when the handler class is dynamic (e.g. read from +config) and when you want a single place that validates the class. + +## Options are case-insensitive + +Option keys are normalised to lower case, so these are all the same option: + +```php +Cache::create(File::class, ['PATH' => '/tmp/cache']); +Cache::create(File::class, ['Path' => '/tmp/cache']); +Cache::create(File::class, ['path' => '/tmp/cache']); +``` + +Options you don't set fall back to the handler's defaults (and the shared +`prefix` default of `cache_`). See [Configuration Options](Configuration-Options.md) +for every default. + +## Reading and changing options later + +Handlers expose two helpers from [`CacheInterface`](API-Reference.md#cacheinterface): + +```php +$cache->getOption('prefix'); // "app_" +$cache->getOption('missing', '-'); // "-" (default when unset) + +$cache->setOptions(['prefix' => 'v2_']); // merge more options in; returns $this +``` + +`setOptions()` merges (case-insensitively) over the current options and returns +the handler, so it chains: + +```php +$cache = (new Redis())->setOptions(['host' => 'cache.internal', 'database' => 2]); +``` + +## When `create()` throws + +`create()` throws a [`CacheException`](Error-Handling.md) in three cases: + +```php +use InitPHP\Cache\Exception\CacheException; + +try { + // 1. The class does not exist + Cache::create('App\\Cache\\Nope'); + + // 2. The class exists but is not a CacheInterface + Cache::create(\stdClass::class); + + // 3. The handler's runtime requirement is missing + // (e.g. Redis without ext-redis) + Cache::create(\InitPHP\Cache\Handler\Redis::class); +} catch (CacheException $e) { + // log / fall back to another handler +} +``` + +The third case happens inside the handler constructor, which calls +`isSupported()` and rejects an unsupported environment. You can pre-check with +`(new Redis())->isSupported()` — see [Installation](Installation.md#checking-a-handler-at-runtime). + +## Next steps + +- [Keys, TTL & Values](Keys-TTL-and-Values.md) — the rules for what you store. +- [Configuration Options](Configuration-Options.md) — every option of every handler. +- [Custom Handlers](Custom-Handlers.md) — pass your own class to `create()`. diff --git a/docs/Troubleshooting.md b/docs/Troubleshooting.md new file mode 100644 index 0000000..e3769d0 --- /dev/null +++ b/docs/Troubleshooting.md @@ -0,0 +1,129 @@ +# Troubleshooting + +Symptoms, likely causes, and fixes. If none fit, +[open an issue](https://github.com/InitPHP/Cache/issues/new) with your PHP +version, handler and a minimal reproduction. + +## `CacheException: … handler is not supported …` + +**Cause:** you built a handler whose extension isn't loaded (e.g. +[Redis](Redis-Handler.md) without `ext-redis`, [Memcache](Memcache-Handler.md) without +`ext-memcached`/`ext-memcache`, or [WinCache](WinCache-Handler.md) when it is not installed, which is the usual +case on PHP 8). + +**Fix:** install/enable the extension, or pre-check and fall back: + +```php +$cache = (new Redis())->isSupported() + ? Cache::create(Redis::class, [...]) + : Cache::create(File::class, ['path' => __DIR__ . '/var/cache']); +``` + +See [Installation](Installation.md#checking-a-handler-at-runtime). + +## `CacheException: The File cache handler requires a … "path" option …` + +**Cause:** the [File handler](File-Handler.md) was created without a `path` (or with +an empty one). + +**Fix:** pass an existing, writable directory: + +```php +$dir = __DIR__ . '/var/cache'; +is_dir($dir) || mkdir($dir, 0775, true); +$cache = Cache::create(File::class, ['path' => $dir]); +``` + +## File handler: `set()` returns `true` but `get()` returns the default + +**Likely causes:** + +- **The directory isn't writable.** `set()` returns `false` when the write fails + — check the return value and the directory permissions/owner. +- **You stored `null`.** A stored `null` is a real hit; `get()` still returns + `null`. Use `has()` to confirm presence. See + [Keys, TTL & Values](Keys-TTL-and-Values.md#null-values). +- **The TTL was `0` or negative**, which deletes the item. + +## `InvalidArgumentException: The cache key … contains a reserved character` + +**Cause:** the key contains one of `{}()/\@:` (often `:` from keys like +`user:42`) or is empty. + +**Fix:** use `.`/`_`, or hash untrusted input: + +```php +$key = 'user_' . $id; // or +$key = 'user_' . hash('xxh3', $raw); // for arbitrary input +``` + +See [Keys, TTL & Values](Keys-TTL-and-Values.md#keys). + +## PDO: every operation returns `false` / a miss + +**Cause:** the cache table doesn't exist or its columns don't match. The PDO +handler returns `false` (rather than throwing) on query-level errors. + +**Fix:** create the table with the correct schema for your driver — see +[PDO Handler → Create the table](PDO-Handler.md#create-the-table). To surface the +underlying error while debugging, query the table yourself with PDO in +`ERRMODE_EXCEPTION` and read the message. + +## PDO: `CacheException: PDO cache connection error …` + +**Cause:** the DSN, credentials or server are wrong/unreachable. Unlike query +errors, a **connection** failure throws. + +**Fix:** verify the `dsn`, `username`, `password` and that the database is +reachable. Wrap construction in a `try/catch` to fall back. See +[Error Handling](Error-Handling.md#failing-soft-on-an-unavailable-backend). + +## PDO: `clear()` removed more/fewer rows than expected + +**Cause:** `clear()` deletes rows whose `name` matches the `prefix`. With an empty +prefix it clears the whole table; with a prefix it matches `prefix%` (wildcards in +the prefix are escaped, so `cache_` matches `cache_*` literally). + +**Fix:** set a distinct `prefix` per application sharing the table. + +## Redis/Memcached: `clear()` wiped data I didn't expect + +**Cause:** `clear()` flushes the **whole** Redis database (`FLUSHDB`) or Memcached +instance (`flush()`), not just your prefix. + +**Fix:** give the cache its own Redis `database` index, or a dedicated Memcached +instance. See [Redis](Redis-Handler.md#how-it-works) / +[Memcache(d)](Memcache-Handler.md#how-it-works). + +## My counter "loses count" after a while + +**Cause:** `increment()` stores **without** a TTL, so a counter you seeded with a +windowed `set($key, 0, $window)` loses its window on the first increment — or an +expiry elsewhere reset it. + +**Fix:** manage the window with `set()` and a rotating key, as in the +[soft rate limiter](Counters.md#counters-and-ttl-a-soft-rate-limiter); or use a +native atomic counter for strict needs. + +## Values come back changed (objects look "different") + +**Cause:** values are stored via `serialize()`/`unserialize()`, so you get an +**equal** object back, not the *same* instance. Resources, closures and PDO +handles can't be cached at all. + +**Fix:** compare with `==`/`assertEquals`, not `===`/`assertSame`, and cache plain +data rather than live objects. + +## Static analysis can't find `\Redis` / `wincache_*` + +**Cause:** you're analysing code that uses an extension you don't have installed. + +**Fix:** install the extension in your analysis environment, or add stub files +(the package itself ships a small WinCache stub for exactly this — see its +`stubs/` directory and `phpstan.neon.dist`). + +## Still stuck? + +Collect your PHP version, the handler and options, and a minimal snippet, then +[open an issue](https://github.com/InitPHP/Cache/issues/new) or ask in +[Discussions](https://github.com/orgs/InitPHP/discussions). diff --git a/docs/WinCache-Handler.md b/docs/WinCache-Handler.md new file mode 100644 index 0000000..ffcbb7c --- /dev/null +++ b/docs/WinCache-Handler.md @@ -0,0 +1,60 @@ +# WinCache Handler + +> ⚠️ **Deprecated.** The WinCache extension is no longer a supported +> Microsoft product and has **no stable release for PHP 8**; only an unsupported +> beta (2.0.0.9, best-effort maintenance) builds on PHP 8.1 and later. This +> handler is kept only for backward compatibility. +> On any modern stack use [File](File-Handler.md), [Redis](Redis-Handler.md) or +> [Memcache(d)](Memcache-Handler.md) instead. + +`InitPHP\Cache\Handler\Wincache` stores items in the WinCache user cache +(`ext-wincache`, Windows only). + +## Options + +| Option | Type | Default | Description | +| --- | --- | --- | --- | +| `prefix` | `string` | `cache_` | Prepended to keys. | +| `default_ttl` | `int` | `0` | Expiry used when `set()` is called **without** a TTL. `0` = no expiry. | + +## Usage + +```php +use InitPHP\Cache\Cache; +use InitPHP\Cache\Handler\Wincache; + +$cache = Cache::create(Wincache::class, [ + 'default_ttl' => 300, +]); + +$cache->set('key', 'value', 60); +$cache->get('key'); +``` + +## How it works + +- Values are stored with `wincache_ucache_set()`; TTLs are delegated to WinCache. +- When `set()` is called without a TTL, the `default_ttl` option is applied + (`0` = no expiry). +- `has()` uses `wincache_ucache_exists()`. +- `clear()` calls **`wincache_ucache_clear()`**, which clears the **entire** + user cache — it is not limited by `prefix`. + +## Requirements + +The handler is only supported when the extension is loaded **and** the user cache +is enabled: + +```php +extension_loaded('wincache') && ini_get('wincache.ucenabled'); // must be true +``` + +Constructing the handler in an unsupported environment throws a +[`CacheException`](Error-Handling.md) — which is what you will get on any runtime +where the extension is not installed and enabled (there is no stable WinCache +release for PHP 8). Build a different handler instead. + +## Next steps + +- [File Handler](File-Handler.md) — the zero-dependency replacement. +- [Configuration Options](Configuration-Options.md) — all handlers side by side. diff --git a/docs/_Footer.md b/docs/_Footer.md new file mode 100644 index 0000000..cab3a35 --- /dev/null +++ b/docs/_Footer.md @@ -0,0 +1,8 @@ +**`initphp/cache`** · MIT License · part of the [InitPHP](https://github.com/InitPHP) family + +[Source](https://github.com/InitPHP/Cache) · +[Issues](https://github.com/InitPHP/Cache/issues) · +[Discussions](https://github.com/orgs/InitPHP/discussions) · +[Packagist](https://packagist.org/packages/initphp/cache) · +[Contributing](https://github.com/InitPHP/.github/blob/main/CONTRIBUTING.md) · +[Security Policy](https://github.com/InitPHP/.github/blob/main/SECURITY.md) diff --git a/docs/_Sidebar.md b/docs/_Sidebar.md new file mode 100644 index 0000000..aa2478a --- /dev/null +++ b/docs/_Sidebar.md @@ -0,0 +1,30 @@ +### [Home](Home.md) + +**Getting Started** +- [Installation](Installation.md) +- [Quick Start](Quick-Start.md) +- [The Cache Factory](The-Cache-Factory.md) + +**Core Concepts** +- [Keys, TTL & Values](Keys-TTL-and-Values.md) +- [Counters](Counters.md) +- [Bulk Operations](Bulk-Operations.md) +- [Error Handling](Error-Handling.md) +- [API Reference](API-Reference.md) + +**Handlers** +- [File](File-Handler.md) +- [PDO](PDO-Handler.md) +- [Redis](Redis-Handler.md) +- [Memcache(d)](Memcache-Handler.md) +- [WinCache](WinCache-Handler.md) +- [Configuration Options](Configuration-Options.md) + +**Guides** +- [Recipes](Recipes.md) +- [Custom Handlers](Custom-Handlers.md) +- [Testing](Testing.md) + +**Other** +- [FAQ](FAQ.md) +- [Troubleshooting](Troubleshooting.md) diff --git a/docs/configuration.md b/docs/configuration.md deleted file mode 100644 index 787105e..0000000 --- a/docs/configuration.md +++ /dev/null @@ -1,78 +0,0 @@ -# Configuration & options - -Options are passed to `Cache::create()` (or a handler constructor) as an -associative array. **Keys are matched case-insensitively** — `prefix`, `Prefix` -and `PREFIX` are the same option. - -You can also merge options into an existing handler with `setOptions()`, and -read one back with `getOption()`: - -```php -$cache = Cache::create(File::class, ['path' => '/tmp/cache']); -$cache->setOptions(['prefix' => 'app_']); -$cache->getOption('prefix'); // "app_" -$cache->getOption('missing', '-'); // "-" -``` - -## Shared option - -| Option | Type | Default | Applies to | -| ------ | ---- | ------- | ---------- | -| `prefix` | `string` | `cache_` | every handler | - -`prefix` is prepended to each key before it reaches the backend, and scopes -`clear()` so one application's cache does not wipe another's that shares the same -store. Set it to `''` to disable prefixing. - -## File - -| Option | Type | Default | Description | -| ------ | ---- | ------- | ----------- | -| `path` | `string` | _(required)_ | Directory the cache files live in. | -| `mode` | `int\|null` | `0640` | `chmod()` mode applied to each file. | - -See [File handler](file-handler.md). - -## PDO - -| Option | Type | Default | Description | -| ------ | ---- | ------- | ----------- | -| `dsn` | `string` | `mysql:host=localhost;dbname=test` | PDO DSN. | -| `username` | `string\|null` | `null` | Connection user. | -| `password` | `string\|null` | `null` | Connection password. | -| `charset` | `string` | `utf8mb4` | MySQL only. | -| `collation` | `string` | `utf8mb4_general_ci` | MySQL only. | -| `table` | `string` | `cache` | Table name (`[A-Za-z0-9_]+`). | - -See [PDO handler](pdo-handler.md). - -## Redis - -| Option | Type | Default | Description | -| ------ | ---- | ------- | ----------- | -| `host` | `string` | `127.0.0.1` | Server host. | -| `port` | `int` | `6379` | Server port. | -| `timeout` | `int\|float` | `0` | Connection timeout (seconds). | -| `password` | `string\|null` | `null` | `AUTH` password. | -| `database` | `int\|null` | `0` | Database index to `SELECT`. | - -See [Redis handler](redis-handler.md). - -## Memcache - -| Option | Type | Default | Description | -| ------ | ---- | ------- | ----------- | -| `host` | `string` | `127.0.0.1` | Server host. | -| `port` | `int` | `11211` | Server port. | -| `weight` | `int` | `1` | Server weight (Memcached). | -| `default_ttl` | `int` | `0` | Expiry used when `set()` gets no TTL. `0` = no expiry. | - -See [Memcache handler](memcache-handler.md). - -## WinCache - -| Option | Type | Default | Description | -| ------ | ---- | ------- | ----------- | -| `default_ttl` | `int` | `0` | Expiry used when `set()` gets no TTL. `0` = no expiry. | - -See [WinCache handler](wincache-handler.md). diff --git a/docs/exceptions.md b/docs/exceptions.md deleted file mode 100644 index 07afd41..0000000 --- a/docs/exceptions.md +++ /dev/null @@ -1,69 +0,0 @@ -# Exceptions - -The library throws two exception types, both under -`InitPHP\Cache\Exception`. Each implements the matching PSR-16 interface, so you -can catch library errors either by the concrete class or through PSR. - -## `CacheException` - -```php -InitPHP\Cache\Exception\CacheException - extends \Exception - implements \Psr\SimpleCache\CacheException -``` - -Thrown for errors that are not about an invalid argument, such as: - -- a required handler extension is missing or disabled - (`Cache::create()` / the constructor); -- a backend connection, authentication or database selection fails - (Redis, Memcache, PDO); -- a required option is missing or invalid (the File `path`, the PDO `table`); -- the factory is given a class that does not exist or does not implement - `CacheInterface`. - -## `InvalidArgumentException` - -```php -InitPHP\Cache\Exception\InvalidArgumentException - extends \InvalidArgumentException - implements \Psr\SimpleCache\InvalidArgumentException -``` - -Thrown when a cache key is invalid — empty, or containing one of the PSR-16 -reserved characters `{}()/\@:`. - -Because `Psr\SimpleCache\InvalidArgumentException` extends -`Psr\SimpleCache\CacheException`, an invalid-key error is also catchable as a -`CacheException`. - -## Catching - -```php -use InitPHP\Cache\Exception\CacheException; -use InitPHP\Cache\Exception\InvalidArgumentException; - -try { - $cache->get($userSuppliedKey); -} catch (InvalidArgumentException $e) { - // The key was empty or contained a reserved character. -} catch (CacheException $e) { - // A configuration or backend error. -} -``` - -Or catch everything the library can throw through the PSR interface: - -```php -use Psr\SimpleCache\CacheException as PsrCacheException; - -try { - $cache->set($key, $value); -} catch (PsrCacheException $e) { - // Any InitPHP\Cache error (invalid key or otherwise). -} -``` - -> Note: PSR-16 read/write methods return `false` (or a default) for ordinary -> backend hiccups rather than throwing. Exceptions are reserved for invalid -> arguments and genuine configuration/connection failures. diff --git a/docs/file-handler.md b/docs/file-handler.md deleted file mode 100644 index f0c955d..0000000 --- a/docs/file-handler.md +++ /dev/null @@ -1,49 +0,0 @@ -# File handler - -`InitPHP\Cache\Handler\File` stores each item as one PHP-serialised file named -`{prefix}{key}` inside a directory you choose. It needs no extension beyond the -PHP core, which makes it a good default and ideal for development. - -## Options - -| Option | Type | Default | Description | -| ------ | ---- | ------- | ----------- | -| `prefix` | `string` | `cache_` | Prepended to keys; also filters `clear()`. | -| `path` | `string` | _(required)_ | Directory the cache files live in. | -| `mode` | `int\|null` | `0640` | `chmod()` mode applied to each file. Set `null` to skip `chmod()`. | - -## Usage - -```php -use InitPHP\Cache\Cache; -use InitPHP\Cache\Handler\File; - -$cache = Cache::create(File::class, [ - 'path' => __DIR__ . '/var/cache', - 'mode' => 0640, -]); - -$cache->set('settings', ['theme' => 'dark'], 3600); -$cache->get('settings'); -``` - -The `path` directory must exist and be writable. If `path` is missing or empty, -operations that touch the filesystem throw a -[`CacheException`](exceptions.md). - -## How it works - -- Each item is `serialize()`d together with its creation time and TTL. -- On read, an expired file is deleted and treated as a miss. -- `clear()` removes only files matching `{prefix}*`, and never deletes the - protective files `.htaccess`, `index.htm`, `index.html`, `index.php` or - `web.config`. - -## Notes - -- **Keep the cache directory out of the web root**, or protect it (the cleared - protective files above exist for directories that cannot be moved). -- Cache files are read with `unserialize()`. Point `path` only at a directory - your application controls — never at attacker-influenced content. -- Very high item counts in a single flat directory can slow the filesystem; pick - a backend like [Redis](redis-handler.md) for large, hot caches. diff --git a/docs/getting-started.md b/docs/getting-started.md deleted file mode 100644 index d78c7e5..0000000 --- a/docs/getting-started.md +++ /dev/null @@ -1,108 +0,0 @@ -# Getting started - -## Install - -```bash -composer require initphp/cache -``` - -Requires PHP 8.0+. Install the extension your chosen handler needs -(`ext-pdo`, `ext-redis`, `ext-memcached`…); the File handler needs nothing -beyond the PHP core. - -## Build a handler - -Use the `Cache::create()` factory. Its first argument is a handler class name -(or an already-built handler instance); the second is an options array. - -```php -require 'vendor/autoload.php'; - -use InitPHP\Cache\Cache; -use InitPHP\Cache\Handler\File; - -$cache = Cache::create(File::class, [ - 'path' => __DIR__ . '/var/cache', - 'prefix' => 'app_', -]); -``` - -`create()` returns an object implementing `InitPHP\Cache\CacheInterface`. If the -class does not exist, does not implement the interface, or the runtime does not -support it (e.g. a missing extension), it throws an -[`InitPHP\Cache\Exception\CacheException`](exceptions.md). - -You can also build a handler directly — the constructor takes the same options: - -```php -use InitPHP\Cache\Handler\File; - -$cache = new File(['path' => __DIR__ . '/var/cache']); -``` - -## Store and read - -```php -$cache->set('greeting', 'Hello'); // no TTL → stored until deleted -$cache->set('token', 'abc', 3600); // 3600 seconds - -$cache->get('greeting'); // "Hello" -$cache->get('unknown'); // null (default) -$cache->get('unknown', 'fallback'); // "fallback" - -$cache->has('greeting'); // true -$cache->delete('greeting'); // true -$cache->clear(); // remove everything this handler owns -``` - -## The read-through pattern - -The most common use: return a cached value, or compute and store it on a miss. - -```php -$report = $cache->get('daily-report'); - -if ($report === null) { - $report = build_expensive_report(); // your code - $cache->set('daily-report', $report, 86400); // cache for a day -} - -return $report; -``` - -> If `null` is a legitimate cached value for you, use `has()` to distinguish a -> miss from a stored `null`: -> -> ```php -> if (!$cache->has('daily-report')) { -> $cache->set('daily-report', $report = build_expensive_report(), 86400); -> } -> $report = $cache->get('daily-report'); -> ``` - -## Bulk operations - -```php -$cache->setMultiple(['a' => 1, 'b' => 2, 'c' => 3], 600); - -$cache->getMultiple(['a', 'b', 'missing'], 0); -// ['a' => 1, 'b' => 2, 'missing' => 0] - -$cache->deleteMultiple(['a', 'b']); -``` - -`getMultiple()`, `setMultiple()` and `deleteMultiple()` accept any `iterable`, -so Generators and other `Traversable`s work too. - -## Counters - -```php -$cache->increment('views'); // 1 -$cache->increment('views', 5); // 6 -$cache->decrement('views', 2); // 4 -$cache->get('views'); // 4 -``` - -See [PSR-16 behaviour & the handler API](psr-16.md) for the exact rules around -keys, TTLs and counters, and [Configuration & options](configuration.md) for -each handler's settings. diff --git a/docs/memcache-handler.md b/docs/memcache-handler.md deleted file mode 100644 index 2d5ea0a..0000000 --- a/docs/memcache-handler.md +++ /dev/null @@ -1,45 +0,0 @@ -# Memcache(d) handler - -`InitPHP\Cache\Handler\Memcache` stores items in Memcached. It works with either -the modern [`Memcached`](https://www.php.net/manual/en/book.memcached.php) -extension (preferred) or the legacy `Memcache` extension; if both are present, -`Memcached` is used. - -## Options - -| Option | Type | Default | Description | -| ------ | ---- | ------- | ----------- | -| `prefix` | `string` | `cache_` | Prepended to keys. | -| `host` | `string` | `127.0.0.1` | Server host. | -| `port` | `int` | `11211` | Server port. | -| `weight` | `int` | `1` | Server weight (Memcached only). | -| `default_ttl` | `int` | `0` | Expiry used when `set()` is called with no TTL. `0` means "no expiry". | - -## Usage - -```php -use InitPHP\Cache\Cache; -use InitPHP\Cache\Handler\Memcache; - -$cache = Cache::create(Memcache::class, [ - 'host' => '127.0.0.1', - 'port' => 11211, -]); - -$cache->set('fragment:nav', $html, 600); -$cache->get('fragment:nav'); -``` - -## How it works - -- Each value is stored as a small serialised envelope, so `null`, `false`, - arrays and objects round-trip exactly. -- TTLs are delegated to the server. When `set()` is called without a TTL, the - `default_ttl` option is used (`0` = no expiry). -- `clear()` calls `flush()`, which clears the **entire** Memcached instance — - it is not limited by `prefix`. - -## Errors - -If neither extension is available, or the server cannot be reached, the handler -throws a [`CacheException`](exceptions.md). diff --git a/docs/pdo-handler.md b/docs/pdo-handler.md deleted file mode 100644 index d00080a..0000000 --- a/docs/pdo-handler.md +++ /dev/null @@ -1,94 +0,0 @@ -# PDO handler - -`InitPHP\Cache\Handler\PDO` stores items in a single database table through PDO. -It is portable across MySQL, SQLite and PostgreSQL: MySQL-specific tuning runs -only on MySQL, and everything else uses plain SQL. Requires `ext-pdo`. - -## Options - -| Option | Type | Default | Description | -| ------ | ---- | ------- | ----------- | -| `prefix` | `string` | `cache_` | Prepended to keys; also filters `clear()`. | -| `dsn` | `string` | `mysql:host=localhost;dbname=test` | PDO DSN. | -| `username` | `string\|null` | `null` | Connection user. | -| `password` | `string\|null` | `null` | Connection password. | -| `charset` | `string` | `utf8mb4` | MySQL only (`SET NAMES`). | -| `collation` | `string` | `utf8mb4_general_ci` | MySQL only. | -| `table` | `string` | `cache` | Table name; must match `[A-Za-z0-9_]+`. | - -## Table schema - -The table needs a unique `name` column, a nullable integer `ttl` (absolute -expiry timestamp) and a text `data` column. - -**MySQL** - -```sql -CREATE TABLE `cache` ( - `name` VARCHAR(255) NOT NULL, - `ttl` INT NULL DEFAULT NULL, - `data` TEXT NOT NULL, - UNIQUE (`name`) -) ENGINE = InnoDB CHARSET = utf8mb4 COLLATE = utf8mb4_general_ci; -``` - -**SQLite** - -```sql -CREATE TABLE cache ( - name VARCHAR(255) NOT NULL, - ttl INTEGER NULL DEFAULT NULL, - data TEXT NOT NULL, - UNIQUE (name) -); -``` - -**PostgreSQL** - -```sql -CREATE TABLE cache ( - name VARCHAR(255) NOT NULL UNIQUE, - ttl INTEGER NULL, - data TEXT NOT NULL -); -``` - -## Usage - -```php -use InitPHP\Cache\Cache; -use InitPHP\Cache\Handler\PDO; - -$cache = Cache::create(PDO::class, [ - 'dsn' => 'mysql:host=127.0.0.1;dbname=app', - 'username' => 'app', - 'password' => 'secret', - 'table' => 'cache', -]); - -$cache->set('feed', $items, 300); -$cache->get('feed'); -``` - -SQLite (including a file or an in-memory database) works the same way: - -```php -$cache = Cache::create(PDO::class, ['dsn' => 'sqlite:' . __DIR__ . '/cache.sqlite']); -``` - -## How it works - -- `set()` upserts (delete + insert in a transaction), so writing the same key - twice overwrites it. -- `ttl` is stored as an absolute expiry timestamp; an expired row is deleted on - read and treated as a miss. -- `clear()` deletes rows whose `name` matches the prefix, escaping `LIKE` - wildcards so a prefix such as `cache_` is matched literally. - -## Errors - -- A connection failure throws a [`CacheException`](exceptions.md). -- An invalid `table` option (anything outside `[A-Za-z0-9_]`) throws a - `CacheException`. -- Query-level failures (for example, a missing table) cause the affected - operation to return `false`/a miss rather than throw. diff --git a/docs/psr-16.md b/docs/psr-16.md deleted file mode 100644 index 5b63c77..0000000 --- a/docs/psr-16.md +++ /dev/null @@ -1,125 +0,0 @@ -# PSR-16 behaviour & the handler API - -Every handler implements `InitPHP\Cache\CacheInterface`: - -```php -namespace InitPHP\Cache; - -interface CacheInterface extends \Psr\SimpleCache\CacheInterface -{ - public function setOptions(array $options = []): static; - public function getOption(string $key, mixed $default = null): mixed; - public function isSupported(): bool; - public function increment(string $key, int $offset = 1): int; - public function decrement(string $key, int $offset = 1): int; -} -``` - -The eight PSR-16 methods (`get`, `set`, `delete`, `clear`, `has`, -`getMultiple`, `setMultiple`, `deleteMultiple`) come from -`Psr\SimpleCache\CacheInterface`. - -## Keys - -A key is any **non-empty string** that does not contain a character reserved by -PSR-16: - -``` -{ } ( ) / \ @ : -``` - -An empty key or one containing a reserved character throws -`InitPHP\Cache\Exception\InvalidArgumentException` (which is both an SPL -`InvalidArgumentException` and a `Psr\SimpleCache\InvalidArgumentException`). - -The configured `prefix` is prepended *after* validation, so the prefix itself is -not subject to the reserved-character rule. - -```php -$cache->get('user.42'); // fine -$cache->get('user:42'); // throws — ":" is reserved -$cache->get(''); // throws — empty -``` - -## Values - -Any value `serialize()` accepts round-trips exactly: strings, integers, floats, -booleans, `null`, arrays and objects. - -```php -$cache->set('n', null); -$cache->has('n'); // true — null was really stored -$cache->get('n', 'default'); // null, not "default" -``` - -`get()` returns the `$default` argument **as-is** on a miss; it is never called, -even when it is a callable. - -## TTL - -`set()` and `setMultiple()` accept `null`, an integer number of seconds, or a -`DateInterval`: - -| TTL | Effect | -| --- | ------ | -| `null` | Store with no expiry (until deleted or evicted). | -| positive `int` | Expire after that many seconds. | -| `DateInterval` | Expire after the interval, measured from now. | -| `0` or negative | Delete the item; `set()` returns `true`. | - -```php -$cache->set('a', 1); // forever -$cache->set('b', 1, 60); // 60 seconds -$cache->set('c', 1, new DateInterval('PT5M')); // 5 minutes -$cache->set('d', 1, 0); // deletes "d" -``` - -> The File and PDO handlers store the expiry and enforce it on read. The Redis, -> Memcache and WinCache handlers delegate expiry to the backend. - -## Bulk methods - -`getMultiple()`, `setMultiple()` and `deleteMultiple()` accept any `iterable` -(arrays, Generators, `Traversable`s): - -```php -function keys(): Generator { - yield 'a'; - yield 'b'; -} - -$cache->getMultiple(keys(), 'default'); -``` - -`getMultiple()` returns a map keyed by the requested keys, with `$default` for -every missing one. `setMultiple()` and `deleteMultiple()` return `true` only -when every individual operation succeeded. - -## Counters - -`increment()` and `decrement()` adjust an integer counter and return the **new -value**. They share one contract across every handler: - -- a missing or non-numeric item is treated as `0`, so `increment('x', 5)` - starts the counter at `5`; -- the result is stored **without an expiry**; -- the stored value is a normal integer, so `get()` reads it back. - -```php -$cache->increment('hits'); // 1 -$cache->increment('hits', 9); // 10 -$cache->decrement('hits', 4); // 6 -$cache->get('hits'); // 6 -``` - -> These counters are read-modify-write operations built on `get()`/`set()`, so -> they are consistent everywhere but **not atomic** across concurrent processes. -> If you need atomic counters under high concurrency, use your backend's native -> facility directly. - -## Capability check - -`isSupported()` reports whether the current runtime can use a handler (for -example, whether the required extension is loaded). The constructor calls it and -throws a `CacheException` when a handler is unsupported, so you rarely need it -directly. diff --git a/docs/redis-handler.md b/docs/redis-handler.md deleted file mode 100644 index bb63b95..0000000 --- a/docs/redis-handler.md +++ /dev/null @@ -1,51 +0,0 @@ -# Redis handler - -`InitPHP\Cache\Handler\Redis` stores items in Redis through the -[phpredis](https://github.com/phpredis/phpredis) extension (`ext-redis`). - -## Options - -| Option | Type | Default | Description | -| ------ | ---- | ------- | ----------- | -| `prefix` | `string` | `cache_` | Prepended to keys. | -| `host` | `string` | `127.0.0.1` | Server host. | -| `port` | `int` | `6379` | Server port. | -| `timeout` | `int\|float` | `0` | Connection timeout in seconds (`0` = unlimited). | -| `password` | `string\|null` | `null` | `AUTH` password; skipped when `null`. | -| `database` | `int\|null` | `0` | Database index to `SELECT`. | - -## Usage - -```php -use InitPHP\Cache\Cache; -use InitPHP\Cache\Handler\Redis; - -$cache = Cache::create(Redis::class, [ - 'host' => '127.0.0.1', - 'port' => 6379, - 'database' => 1, - 'password' => null, -]); - -$cache->set('session:abc', $payload, 1800); -$cache->get('session:abc'); -``` - -## How it works - -- Each value is stored as a small serialised envelope, so `null`, `false`, - arrays and objects round-trip exactly. -- TTLs are delegated to Redis (`SETEX`); items with no TTL never expire. -- `clear()` runs `FLUSHDB`, clearing the **whole selected database** regardless - of `prefix`. Point the handler at a dedicated `database` if you need isolation. - -## Errors - -A failed connection, authentication or database selection throws a -[`CacheException`](exceptions.md) that wraps the underlying `RedisException`. - -## Pure-PHP alternative - -This handler requires the C extension. If you cannot install `ext-redis`, use a -PSR-16 adapter over a pure-PHP client (such as Predis) instead, or fall back to -the [PDO](pdo-handler.md) or [File](file-handler.md) handler. diff --git a/docs/wincache-handler.md b/docs/wincache-handler.md deleted file mode 100644 index 5b9bc30..0000000 --- a/docs/wincache-handler.md +++ /dev/null @@ -1,40 +0,0 @@ -# WinCache handler - -> **Deprecated.** The WinCache extension is unmaintained and is not available -> for PHP 8. This handler is kept only for backward compatibility. On modern -> stacks use [File](file-handler.md), [Redis](redis-handler.md) or -> [Memcache(d)](memcache-handler.md) instead. - -`InitPHP\Cache\Handler\Wincache` stores items in the WinCache user cache -(`ext-wincache`, Windows only). - -## Options - -| Option | Type | Default | Description | -| ------ | ---- | ------- | ----------- | -| `prefix` | `string` | `cache_` | Prepended to keys. | -| `default_ttl` | `int` | `0` | Expiry used when `set()` is called with no TTL. `0` means "no expiry". | - -## Usage - -```php -use InitPHP\Cache\Cache; -use InitPHP\Cache\Handler\Wincache; - -$cache = Cache::create(Wincache::class, [ - 'default_ttl' => 300, -]); - -$cache->set('key', 'value', 60); -$cache->get('key'); -``` - -## How it works - -- Values are stored with `wincache_ucache_set()`; TTLs are delegated to WinCache. -- `clear()` calls `wincache_ucache_clear()`, clearing the **entire** user cache. - -## Errors - -If the WinCache extension is not loaded, or `wincache.ucenabled` is off, -constructing the handler throws a [`CacheException`](exceptions.md).