ApcuManager
in package
ApcuManager
Professional APCu wrapper with namespace support, TTL handling, atomic operations, bulk helpers and cleanup utilities.
Requirements:
- ext-apcu installed and enabled
- for CLI usage you may need apc.enable_cli=1
Table of Contents
Properties
- $defaultTtl : int
- $namespace : string
- $strict : bool
Methods
- __construct() : mixed
- Create a new APCu cache instance.
- add() : bool
- Store a value only if the key does not already exist.
- all() : array<string, mixed>
- Return all key-value pairs in this namespace.
- clearNamespace() : int
- Clear only current namespace.
- compareAndSwap() : bool
- Compare-and-swap for integer values.
- decrement() : int|false
- Atomically decrement a numeric key.
- delete() : bool
- Delete a single key from the cache.
- deleteMultiple() : bool
- Delete multiple keys from the cache.
- ensureAvailable() : void
- Throw if APCu is unavailable and strict mode is enabled.
- exists() : bool
- Alias for has().
- flush() : bool
- Flush all APCu cache entries globally.
- get() : mixed
- Fetch a value from the cache.
- getDefaultTtl() : int
- Get the current default TTL.
- getMultiple() : array<string, mixed>
- Fetch multiple values from the cache at once.
- getNamespace() : string
- Get the current namespace.
- has() : bool
- Check if a key exists in the cache.
- increment() : int|false
- Atomically increment a numeric key.
- isAvailable() : bool
- Check if APCu is available and enabled.
- key() : string
- Build a namespaced APCu key.
- keys() : array<string|int, string>
- Return all keys in this namespace.
- memoryInfo() : array<string|int, mixed>
- APCu shared memory info.
- purgeByPattern() : int
- Purge all keys matching a regex against namespace-local key.
- purgeByPrefix() : int
- Purge all keys matching a namespace-local prefix.
- put() : bool
- Alias for set().
- remember() : mixed
- Remember pattern - computes and caches a value only if it's not already cached.
- rememberUntil() : mixed
- Remember a value until a specific DateTime.
- replace() : bool
- Replace existing value only.
- set() : bool
- Store a value in the cache.
- setDefaultTtl() : static
- Set a new default TTL for this cache instance.
- setMultiple() : bool
- Store multiple values in the cache at once.
- setNamespace() : static
- Set a new namespace for this cache instance.
- setUntil() : bool
- Set a value with an absolute expiration date.
- stats() : array<string|int, mixed>
- APCu cache info.
- touch() : bool
- Refresh TTL of an existing key, preserving its current value.
- ttlUntil() : int
- Convert DateTime expiration to TTL in seconds.
- extractEntryKey() : string|null
- Return a raw namespaced key list element if possible.
- normalizeNamespace() : string
- Normalize namespace to a safe cache prefix.
- normalizeTtl() : int
- Normalize TTL value for cache operations.
Properties
$defaultTtl
private
int
$defaultTtl
$namespace
private
string
$namespace
$strict
private
bool
$strict
Methods
__construct()
Create a new APCu cache instance.
public
__construct([string $namespace = 'app' ][, int $defaultTtl = 3600 ][, bool $strict = true ]) : mixed
Parameters
- $namespace : string = 'app'
-
Cache namespace for key isolation
- $defaultTtl : int = 3600
-
Default time-to-live in seconds (0 = infinite)
- $strict : bool = true
-
Whether to throw exceptions when APCu is unavailable
add()
Store a value only if the key does not already exist.
public
add(string $key, mixed $value[, int|null $ttl = null ]) : bool
Parameters
- $key : string
-
The cache key
- $value : mixed
-
The value to store
- $ttl : int|null = null
-
Time-to-live in seconds (null for default)
Return values
bool —True if the value was stored successfully, false otherwise
all()
Return all key-value pairs in this namespace.
public
all([bool $stripNamespace = true ]) : array<string, mixed>
This method retrieves all cache entries that belong to the current namespace and returns them as an associative array. It can optionally strip the namespace prefix from the keys in the returned array.
Parameters
- $stripNamespace : bool = true
-
If true, removes the namespace prefix from keys (default: true)
Return values
array<string, mixed> —An associative array of all key-value pairs in the namespace
clearNamespace()
Clear only current namespace.
public
clearNamespace() : int
This method removes all cache entries that belong to the current namespace but preserves other cache entries. It's equivalent to purging by an empty prefix.
Return values
int —Number of deleted keys
compareAndSwap()
Compare-and-swap for integer values.
public
compareAndSwap(string $key, int $old, int $new) : bool
APCu CAS works on integers.
This method implements a compare-and-swap operation for integer cache values. It atomically replaces the value of a key only if the current value matches the expected old value. This is useful for implementing locks or ensuring atomic updates to numeric counters.
Parameters
- $key : string
-
The cache key to modify
- $old : int
-
The expected current value
- $new : int
-
The new value to set if current matches expected
Return values
bool —True if the swap was successful, false otherwise
decrement()
Atomically decrement a numeric key.
public
decrement(string $key[, int $step = 1 ][, int|null $ttl = null ][, int $initial = 0 ]) : int|false
If key does not exist, it is initialized to $initial - $step.
This method performs an atomic operation to decrement a numeric cache entry. If the key doesn't exist, it's initialized with the value of $initial - $step and that value is returned. The operation is atomic, preventing race conditions in multi-process or multi-threaded environments.
Parameters
- $key : string
-
The cache key to decrement
- $step : int = 1
-
The amount to decrement by (default: 1)
- $ttl : int|null = null
-
Time-to-live in seconds (null for default TTL)
- $initial : int = 0
-
The initial value when key doesn't exist (default: 0)
Return values
int|false —Returns the new value on success, or false on failure
delete()
Delete a single key from the cache.
public
delete(string $key) : bool
Parameters
- $key : string
-
The cache key to delete
Return values
bool —True if the key was deleted successfully, false otherwise
deleteMultiple()
Delete multiple keys from the cache.
public
deleteMultiple(array<string|int, string> $keys) : bool
Parameters
- $keys : array<string|int, string>
-
Array of cache keys to delete
Return values
bool —True if all keys were deleted successfully, false otherwise
ensureAvailable()
Throw if APCu is unavailable and strict mode is enabled.
public
ensureAvailable() : void
Tags
exists()
Alias for has().
public
exists(string $key) : bool
Parameters
- $key : string
-
The cache key
Return values
bool —True if key exists, false otherwise
flush()
Flush all APCu cache entries globally.
public
flush() : bool
This method clears the entire APCu cache, removing all cached entries. Use carefully as this affects all cached data, not just the current namespace.
Return values
bool —True on success, false on failure
get()
Fetch a value from the cache.
public
get(string $key[, mixed $default = null ]) : mixed
Parameters
- $key : string
-
The cache key
- $default : mixed = null
-
Default value to return if key is not found
Return values
mixed —The cached value or default if not found
getDefaultTtl()
Get the current default TTL.
public
getDefaultTtl() : int
Return values
int —Current default TTL in seconds
getMultiple()
Fetch multiple values from the cache at once.
public
getMultiple(array<string|int, string> $keys[, mixed $default = null ]) : array<string, mixed>
This method provides a batch operation to retrieve multiple values from the cache simultaneously. It's more efficient than calling get() multiple times when retrieving several related values.
Parameters
- $keys : array<string|int, string>
-
Array of cache keys to retrieve
- $default : mixed = null
-
Default value to return if key is not found
Return values
array<string, mixed> —Associative array of retrieved key-value pairs
getNamespace()
Get the current namespace.
public
getNamespace() : string
Return values
string —Current namespace
has()
Check if a key exists in the cache.
public
has(string $key) : bool
Parameters
- $key : string
-
The cache key
Return values
bool —True if key exists, false otherwise
increment()
Atomically increment a numeric key.
public
increment(string $key[, int $step = 1 ][, int|null $ttl = null ][, int $initial = 0 ]) : int|false
If key does not exist, it is initialized to $initial + $step.
This method performs an atomic operation to increment a numeric cache entry. If the key doesn't exist, it's initialized with the value of $initial + $step and that value is returned. The operation is atomic, preventing race conditions in multi-process or multi-threaded environments.
Parameters
- $key : string
-
The cache key to increment
- $step : int = 1
-
The amount to increment by (default: 1)
- $ttl : int|null = null
-
Time-to-live in seconds (null for default TTL)
- $initial : int = 0
-
The initial value when key doesn't exist (default: 0)
Return values
int|false —Returns the new value on success, or false on failure
isAvailable()
Check if APCu is available and enabled.
public
isAvailable() : bool
Return values
bool —True if APCu is available and enabled, false otherwise
key()
Build a namespaced APCu key.
public
key(string $key) : string
Parameters
- $key : string
-
The original cache key
Return values
string —Fully qualified cache key with namespace
keys()
Return all keys in this namespace.
public
keys([bool $stripNamespace = true ]) : array<string|int, string>
This method retrieves all cache keys that belong to the current namespace. It filters the APCu cache entries to return only those that match the current namespace prefix and returns either full keys or just the local part depending on the stripNamespace parameter.
Parameters
- $stripNamespace : bool = true
-
If true, returns only the local part of keys (default: true)
Return values
array<string|int, string> —List of cache keys in this namespace
memoryInfo()
APCu shared memory info.
public
memoryInfo() : array<string|int, mixed>
This method returns information about the shared memory used by APCu, including allocation status and memory usage details.
Return values
array<string|int, mixed> —Information about APCu shared memory
purgeByPattern()
Purge all keys matching a regex against namespace-local key.
public
purgeByPattern(string $pattern) : int
This method removes all cache entries whose local keys (without namespace) match the provided regular expression pattern. It's useful for removing cache entries based on more complex matching rules.
Parameters
- $pattern : string
-
The regular expression pattern to match against local keys
Return values
int —Number of deleted keys
purgeByPrefix()
Purge all keys matching a namespace-local prefix.
public
purgeByPrefix([string $prefix = '' ]) : int
This method removes all cache entries whose local keys (without namespace) start with the specified prefix. It's useful for cleaning up related cache entries.
Parameters
- $prefix : string = ''
-
The prefix to match against local keys
Tags
Return values
int —Number of deleted keys
put()
Alias for set().
public
put(string $key, mixed $value[, int|null $ttl = null ]) : bool
Parameters
- $key : string
-
The cache key
- $value : mixed
-
The value to store
- $ttl : int|null = null
-
Time-to-live in seconds (null for default)
Return values
bool —True if the value was stored successfully, false otherwise
remember()
Remember pattern - computes and caches a value only if it's not already cached.
public
remember(string $key, callable $callback[, int|null $ttl = null ]) : mixed
This method implements a "remember" pattern where the callback is executed only when the key doesn't exist in cache. It ensures that expensive operations are performed only once, with subsequent calls returning the cached value.
Parameters
- $key : string
-
The cache key to check or set
- $callback : callable
-
Function that computes the value if not cached
- $ttl : int|null = null
-
Time-to-live in seconds (null for default TTL)
Return values
mixed —The cached or computed value
rememberUntil()
Remember a value until a specific DateTime.
public
rememberUntil(string $key, callable $callback, DateTimeInterface $expiresAt) : mixed
This method implements a "remember" pattern with absolute expiration time. It's useful when you want to cache values for a specific duration from now, rather than relative TTL.
Parameters
- $key : string
-
The cache key to check or set
- $callback : callable
-
Function that computes the value if not cached
- $expiresAt : DateTimeInterface
-
The date/time when the cached value should expire
Return values
mixed —The cached or computed value
replace()
Replace existing value only.
public
replace(string $key, mixed $value[, int|null $ttl = null ]) : bool
Parameters
- $key : string
-
The cache key
- $value : mixed
-
The value to store
- $ttl : int|null = null
-
Time-to-live in seconds (null for default)
Return values
bool —True if the value was stored successfully, false otherwise
set()
Store a value in the cache.
public
set(string $key, mixed $value[, int|null $ttl = null ]) : bool
Parameters
- $key : string
-
The cache key
- $value : mixed
-
The value to store
- $ttl : int|null = null
-
Time-to-live in seconds (null for default)
Return values
bool —True if the value was stored successfully, false otherwise
setDefaultTtl()
Set a new default TTL for this cache instance.
public
setDefaultTtl(int $seconds) : static
Parameters
- $seconds : int
-
New default TTL in seconds
Return values
staticsetMultiple()
Store multiple values in the cache at once.
public
setMultiple(array<string, mixed> $values[, int|null $ttl = null ]) : bool
This method provides a batch operation to store multiple key-value pairs in the cache simultaneously. It ensures that all values are stored with consistent TTL handling, though it doesn't provide atomicity across all operations if one fails during the process.
Parameters
- $values : array<string, mixed>
-
An associative array of key-value pairs to store
- $ttl : int|null = null
-
Time-to-live in seconds (null for default TTL)
Return values
bool —True if all values were stored successfully, false otherwise
setNamespace()
Set a new namespace for this cache instance.
public
setNamespace(string $namespace) : static
Parameters
- $namespace : string
-
New namespace to use
Return values
staticsetUntil()
Set a value with an absolute expiration date.
public
setUntil(string $key, mixed $value, DateTimeInterface $expiresAt) : bool
This method stores a cache entry that will expire at the specified absolute time, rather than after a relative time interval. It's useful for implementing time-based caching strategies.
Parameters
- $key : string
-
The cache key to set
- $value : mixed
-
The value to store
- $expiresAt : DateTimeInterface
-
The date/time when the cached value should expire
Return values
bool —True if the value was stored successfully, false otherwise
stats()
APCu cache info.
public
stats() : array<string|int, mixed>
This method returns detailed information about the APCu cache, including statistics and metadata about cached entries.
Return values
array<string|int, mixed> —Information about the APCu cache
touch()
Refresh TTL of an existing key, preserving its current value.
public
touch(string $key[, int|null $ttl = null ]) : bool
This method extends the lifetime of an existing cache entry by resetting its time-to-live without changing its value. This is useful for implementing "sliding window" expiration or preventing premature cache invalidation.
Parameters
- $key : string
-
The cache key to touch
- $ttl : int|null = null
-
New time-to-live in seconds (null to preserve existing TTL)
Return values
bool —True if the operation was successful, false otherwise
ttlUntil()
Convert DateTime expiration to TTL in seconds.
public
ttlUntil(DateTimeInterface $expiresAt) : int
This method calculates the time-to-live by finding the difference between the provided expiration timestamp and the current timestamp. If the calculated TTL is negative (meaning the expiration has already passed), it returns 0. This ensures that expired entries are treated as having zero TTL.
Parameters
- $expiresAt : DateTimeInterface
-
The date/time when the cache entry should expire
Return values
int —The time-to-live in seconds (0 if already expired)
extractEntryKey()
Return a raw namespaced key list element if possible.
private
extractEntryKey(array<string|int, mixed> $entry) : string|null
This method attempts to extract a usable key from a cache entry array. It checks for the presence of 'info' or 'key' keys and returns their string values if they exist. The 'info' key takes precedence over 'key' when both are present. If neither is found or is not a string, it returns null.
Parameters
- $entry : array<string|int, mixed>
-
The cache entry to extract the key from
Return values
string|null —The extracted key or null if not found
normalizeNamespace()
Normalize namespace to a safe cache prefix.
private
normalizeNamespace(string $namespace) : string
This method sanitizes and validates a namespace string to ensure it's safe for use as a cache key prefix. It trims whitespace and replaces invalid characters with underscores, then validates that the result is not empty.
Parameters
- $namespace : string
-
The namespace to normalize
Tags
Return values
string —The normalized namespace
normalizeTtl()
Normalize TTL value for cache operations.
private
normalizeTtl(int|null $ttl) : int
This method ensures that a TTL value is properly normalized for cache operations. If the provided TTL is null, it defaults to the instance's default TTL. Otherwise, it returns the maximum of 0 and the provided TTL to ensure non-negative values.
Parameters
- $ttl : int|null
-
The TTL in seconds, or null to use default
Return values
int —The normalized TTL (non-negative integer)