Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
32 changes: 19 additions & 13 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand All @@ -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

Expand Down
193 changes: 193 additions & 0 deletions docs/API-Reference.md
Original file line number Diff line number Diff line change
@@ -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).

<h3 id="increment"><code>increment()</code> / <code>decrement()</code></h3>

```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.
116 changes: 116 additions & 0 deletions docs/Bulk-Operations.md
Original file line number Diff line number Diff line change
@@ -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.
Loading
Loading