Cargo
in package
Class Cargo
cargo – a super‑light, static key/value container with optional TTL, versioning, and safety rails.
Think of it as an in‑memory "miscellaneous drawer" you can open anywhere in your codebase. Each named container (default is "default") is:
• Singleton‑scoped – \Primordyx\Cargo::getInstance('foo')
always returns the
same object for a given name.
• Globally shared – the data lives in a static array, so every request to that container sees the same state.
Core features
CRUD helpers – set()
, get()
, has()
, forget()
, flush()
.
TTL support – store temp data that auto‑expires ($ttl
in seconds).
Lazy values – lazy($key, fn() => heavy())
only runs the callback once.
Snapshots / restore – snapshot()
versions the whole container; restore()
rolls back.
Diff & merge – static helpers compare or merge two containers.
Protection & lg
– Protect individual keys from mutation (protect()
).
– Lock an entire container from writes (lock()
).
Logging – every mutating call is logged (getLog()
, pruneLog()
, global setLogLimit()
), capped at 1000 by default.
Persistence – save/load to JSON file or PHP session.
Helpers – bulk import/export, JSON serialization (toJSON()
), key list, null‑to‑empty‑string fallback (nullsAreEmptyStrings()
).
Intended use‑cases
- Stashing request‑wide or application‑wide context that doesn't merit a dedicated class (e.g. feature flags, breadcrumb trails, debug data).
- Quick‑and‑dirty caching of computed values.
- Coordinating data between legacy procedural code and newer class‑based modules without wiring a DI container.
NOT a replacement for a real cache or queue – it lives only as long as the PHP process/request.
Tags
Table of Contents
Properties
- $globalEmptyStringFallback : bool
- $dirtyFlags : array<string|int, mixed>
- $instances : array<string|int, mixed>
- $locks : array<string|int, mixed>
- $logLimit : int
- $logs : array<string|int, mixed>
- $name : string
- $objects : array<string|int, mixed>
- $protected : array<string|int, mixed>
- $returnEmptyStringForNull : bool
- $versions : array<string|int, mixed>
Methods
- addToArray() : void
- Appends a value to an array stored under the specified key.
- all() : array<string|int, mixed>
- Alias for dump() - returns all container data.
- allInstances() : array<string, array<string|int, mixed>>
- Returns all container data arrays indexed by container name.
- clearFromSession() : void
- Removes all Cargo data from the PHP session.
- copy() : void
- Copies all data from one container to another.
- diff() : array<string|int, mixed>
- Compares two containers and returns the differences.
- dump() : array<string|int, mixed>
- Returns a copy of all data in the container.
- exists() : bool
- Checks if a named container exists in the registry.
- flush() : void
- Removes all data from the container.
- forget() : void
- Removes a key from the container.
- forgetAll() : void
- Clears all containers and their associated metadata.
- get() : mixed
- Retrieves a value from the container with optional default fallback.
- getExpiresAt() : int|null
- Gets the expiration timestamp for a TTL-enabled key.
- getInstance() : self
- Gets or creates a singleton Cargo container instance by name.
- getLog() : array<string|int, mixed>
- Retrieves the operation log for this container with optional filtering.
- getLogLimit() : int
- Gets the current global log limit.
- getName() : string
- Gets the name of this container instance.
- has() : bool
- Checks if a key exists in the container and hasn't expired.
- isDirty() : bool
- Checks if this container has been modified since creation or last clean state.
- isLocked() : bool
- Checks if the container is locked against write operations.
- isProtected() : bool
- Checks if a key is protected from modification.
- keys() : array<string|int, mixed>
- Returns an array of all keys in the container.
- lazy() : mixed
- Lazily evaluates and caches the result of a callback.
- listVersions() : array<string|int, mixed>
- Returns a list of all available snapshot version names for this container.
- loadFromArray() : void
- Replaces all container data with the provided array.
- loadFromFile() : bool
- Loads container data from a JSON file.
- loadFromSafe() : void
- Loads container instances from the Safe session system.
- loadFromSession() : void
- Loads container instances from the PHP session.
- lock() : void
- Locks the container against all write operations.
- log() : void
- Logs an operation for this container instance.
- merge() : void
- Merges data from one container into another with optional overwrite control.
- mergeArray() : void
- Merges an array into the container with optional overwrite control.
- nullsAreEmptyStrings() : static
- Configures null-to-empty-string conversion for this container or globally.
- on() : self
- Creates a temporary Cargo instance that doesn't persist in the singleton registry.
- protect() : void
- Protects a key from modification or deletion.
- pruneLog() : void
- Manually prunes the operation log to keep only recent entries.
- pull() : mixed
- Retrieves and removes a key from the container in one operation.
- purgeExpired() : void
- Removes all expired TTL entries from the container.
- remember() : mixed
- Returns a value if it exists, otherwise sets and returns the provided default.
- removeContainer() : void
- Completely removes a container and all associated metadata.
- removeFromSafe() : void
- Removes all Cargo data from the Safe session system.
- restore() : bool
- Restores the container to a previously saved snapshot version.
- saveToFile() : bool
- Saves the container data to a JSON file.
- saveToSafe() : void
- Saves all container instances to the Safe session system.
- saveToSession() : void
- Saves all container instances to the PHP session.
- set() : void
- Stores a value in the container with optional TTL expiration.
- setDirty() : void
- Manually sets the dirty flag for this container.
- setLogLimit() : void
- Sets the global limit for log entries per container.
- shouldReturnEmptyStringForNull() : bool
- Checks if this container instance is configured to return empty strings for null defaults.
- shouldReturnEmptyStringsGlobally() : bool
- Checks if the global null-to-empty-string fallback is enabled.
- snapshot() : string
- Creates a versioned snapshot of the current container state.
- toJSON() : string
- Serializes the container data to a JSON string.
- __construct() : mixed
- Initializes a new Cargo container instance with the specified name.
- logStatic() : void
- Static method for logging operations on named containers.
- resolveDefault() : mixed
- Resolves default values with null-to-empty-string conversion if enabled.
Properties
$globalEmptyStringFallback
protected
static bool
$globalEmptyStringFallback
= false
$dirtyFlags
private
static array<string|int, mixed>
$dirtyFlags
= []
$instances
private
static array<string|int, mixed>
$instances
= []
$locks
private
static array<string|int, mixed>
$locks
= []
$logLimit
private
static int
$logLimit
= 1000
$logs
private
static array<string|int, mixed>
$logs
= []
$name
private
string
$name
$objects
private
static array<string|int, mixed>
$objects
= []
$protected
private
static array<string|int, mixed>
$protected
= []
$returnEmptyStringForNull
private
bool
$returnEmptyStringForNull
= false
$versions
private
static array<string|int, mixed>
$versions
= []
Methods
addToArray()
Appends a value to an array stored under the specified key.
public
addToArray(string $arrayKey, mixed $value) : void
If the key doesn't exist, creates a new array. If the existing value is not an array, replaces it with a new array containing the new value.
Parameters
- $arrayKey : string
-
The key containing the array to append to.
- $value : mixed
-
The value to append to the array.
Tags
all()
Alias for dump() - returns all container data.
public
all() : array<string|int, mixed>
Tags
Return values
array<string|int, mixed> —A copy of all container data.
allInstances()
Returns all container data arrays indexed by container name.
public
static allInstances() : array<string, array<string|int, mixed>>
Provides access to the raw data structures for all registered containers. Useful for debugging, serialization, or advanced container manipulation.
Tags
Return values
array<string, array<string|int, mixed>> —All container data keyed by container name.
clearFromSession()
Removes all Cargo data from the PHP session.
public
static clearFromSession() : void
Cleans up session storage by removing the Cargo instances data. Automatically starts the session if not already active.
Tags
copy()
Copies all data from one container to another.
public
static copy(string $from, string $to) : void
Creates an exact duplicate of the source container's data in the destination container, overwriting any existing data.
Parameters
- $from : string
-
The source container name.
- $to : string
-
The destination container name.
Tags
diff()
Compares two containers and returns the differences.
public
static diff(string $a, string $b) : array<string|int, mixed>
Analyzes two named containers and returns arrays of added, removed, and changed keys between them.
Parameters
- $a : string
-
The first container name.
- $b : string
-
The second container name.
Tags
Return values
array<string|int, mixed> —An associative array with 'added', 'removed', and 'changed' keys.
dump()
Returns a copy of all data in the container.
public
dump() : array<string|int, mixed>
Provides access to the raw container data including TTL metadata. The returned array is a copy, so modifications won't affect the container.
Tags
Return values
array<string|int, mixed> —A copy of all container data.
exists()
Checks if a named container exists in the registry.
public
static exists(string $name) : bool
Parameters
- $name : string
-
The container name to check.
Tags
Return values
bool —True if the container exists, false otherwise.
flush()
Removes all data from the container.
public
flush() : void
Clears the entire container while respecting lock status. Locked containers cannot be flushed.
Tags
forget()
Removes a key from the container.
public
forget(string $key) : void
Respects container locks and key protection. Blocked operations are logged but don't throw exceptions.
Parameters
- $key : string
-
The key to remove.
Tags
forgetAll()
Clears all containers and their associated metadata.
public
static forgetAll() : void
Removes all container data, object instances, locks, protections, dirty flags, and version snapshots. A complete reset operation.
Tags
get()
Retrieves a value from the container with optional default fallback.
public
get(string $key[, mixed $default = null ]) : mixed
Automatically handles TTL expiration by removing expired entries. Supports null-to-empty-string conversion if configured.
Parameters
- $key : string
-
The storage key to retrieve.
- $default : mixed = null
-
The value to return if the key doesn't exist or has expired.
Tags
Return values
mixed —The stored value, or the default if not found/expired.
getExpiresAt()
Gets the expiration timestamp for a TTL-enabled key.
public
getExpiresAt(string $key) : int|null
Returns the Unix timestamp when the key will expire, or null if the key has no TTL or doesn't exist.
Parameters
- $key : string
-
The key to check expiration for.
Tags
Return values
int|null —The expiration timestamp, or null if no TTL set.
getInstance()
Gets or creates a singleton Cargo container instance by name.
public
static getInstance([string $name = 'default' ]) : self
This is the primary entry point for accessing named containers. Each unique name returns the same instance throughout the application lifecycle.
Parameters
- $name : string = 'default'
-
The container name. Defaults to 'default'.
Tags
Return values
self —The singleton container instance for the given name.
getLog()
Retrieves the operation log for this container with optional filtering.
public
getLog([string $filterPrefix = '' ]) : array<string|int, mixed>
Returns an array of logged operations with timestamps, actions, keys, and values. Can be filtered by action prefix for targeted debugging.
Parameters
- $filterPrefix : string = ''
-
Optional prefix to filter log entries by action.
Tags
Return values
array<string|int, mixed> —An array of log entries matching the filter criteria.
getLogLimit()
Gets the current global log limit.
public
static getLogLimit() : int
Tags
Return values
int —The maximum number of log entries kept per container.
getName()
Gets the name of this container instance.
public
getName() : string
Tags
Return values
string —The container's unique name identifier.
has()
Checks if a key exists in the container and hasn't expired.
public
has(string $key) : bool
This method handles TTL expiration by automatically removing expired entries and returning false for them.
Parameters
- $key : string
-
The key to check for existence.
Tags
Return values
bool —True if the key exists and hasn't expired, false otherwise.
isDirty()
Checks if this container has been modified since creation or last clean state.
public
isDirty() : bool
The dirty flag tracks whether any mutating operations have occurred, helping with persistence decisions and change detection.
Tags
Return values
bool —True if the container has been modified, false otherwise.
isLocked()
Checks if the container is locked against write operations.
public
isLocked() : bool
Tags
Return values
bool —True if the container is locked, false otherwise.
isProtected()
Checks if a key is protected from modification.
public
isProtected(string $key) : bool
Parameters
- $key : string
-
The key to check protection status for.
Tags
Return values
bool —True if the key is protected, false otherwise.
keys()
Returns an array of all keys in the container.
public
keys() : array<string|int, mixed>
Tags
Return values
array<string|int, mixed> —An array of string keys currently in the container.
lazy()
Lazily evaluates and caches the result of a callback.
public
lazy(string $key, callable $callback) : mixed
If the key exists, returns the stored value. If not, executes the callback, stores the result, and returns it. Useful for expensive computations.
Parameters
- $key : string
-
The cache key for the computed value.
- $callback : callable
-
The function to execute if the key doesn't exist.
Tags
Return values
mixed —The cached or newly computed value.
listVersions()
Returns a list of all available snapshot version names for this container.
public
listVersions() : array<string|int, mixed>
Tags
Return values
array<string|int, mixed> —An array of version names that can be used with restore().
loadFromArray()
Replaces all container data with the provided array.
public
loadFromArray(array<string|int, mixed> $data) : void
Completely overwrites the container contents and resets the dirty flag. Respects container locks.
Parameters
- $data : array<string|int, mixed>
-
The data to load into the container.
Tags
loadFromFile()
Loads container data from a JSON file.
public
loadFromFile(string $filepath) : bool
Reads and parses a JSON file, then loads the data into the container. The operation is logged and overwrites existing container data.
Parameters
- $filepath : string
-
The file path to load JSON data from.
Tags
Return values
bool —True if the file was loaded successfully, false otherwise.
loadFromSafe()
Loads container instances from the Safe session system.
public
static loadFromSafe() : void
Restores previously saved Cargo state from the Safe session and resets dirty flags. Automatically ensures Safe is started before loading.
Tags
loadFromSession()
Loads container instances from the PHP session.
public
static loadFromSession() : void
Restores previously saved Cargo state from the session and resets dirty flags. Automatically starts the session if not already active.
Tags
lock()
Locks the container against all write operations.
public
lock() : void
Prevents any modifications to the container including set(), forget(), flush(), and merge operations. Useful for read-only modes.
Tags
log()
Logs an operation for this container instance.
public
log(string $action[, string $key = '' ][, mixed $value = null ]) : void
Records container operations with timestamp, action, key, and value for debugging and auditing purposes.
Parameters
- $action : string
-
The action being performed (e.g., 'set', 'get', 'forget').
- $key : string = ''
-
The key involved in the operation.
- $value : mixed = null
-
The value involved in the operation.
Tags
merge()
Merges data from one container into another with optional overwrite control.
public
static merge(string $from, string $to[, bool $overwrite = false ]) : void
Combines data from the source container into the destination container, with control over whether existing keys should be overwritten.
Parameters
- $from : string
-
The source container name.
- $to : string
-
The destination container name.
- $overwrite : bool = false
-
Whether to overwrite existing keys in the destination.
Tags
mergeArray()
Merges an array into the container with optional overwrite control.
public
mergeArray(array<string|int, mixed> $data[, bool $overwrite = false ]) : void
Adds or updates keys from the provided array while optionally preserving existing values. Respects locks and key protection.
Parameters
- $data : array<string|int, mixed>
-
The data to merge into the container.
- $overwrite : bool = false
-
Whether to overwrite existing keys. Defaults to false.
Tags
nullsAreEmptyStrings()
Configures null-to-empty-string conversion for this container or globally.
public
nullsAreEmptyStrings([bool $toggle = true ][, bool $makeGlobal = false ]) : static
When enabled, null default values are converted to empty strings when retrieving non-existent keys. Can be set per-instance or globally.
Parameters
- $toggle : bool = true
-
Whether to enable null-to-empty-string conversion.
- $makeGlobal : bool = false
-
Whether to apply this setting globally to new containers.
Tags
Return values
static —Returns the container instance for method chaining.
on()
Creates a temporary Cargo instance that doesn't persist in the singleton registry.
public
static on(string $name) : self
Unlike getInstance()
, this method creates a new container instance each time
it's called, without storing it in the global registry. Useful for temporary
containers or testing scenarios.
Parameters
- $name : string
-
The container name for this temporary instance.
Tags
Return values
self —A new, non-persistent container instance.
protect()
Protects a key from modification or deletion.
public
protect(string $key) : void
Protected keys cannot be changed via set(), forget(), or other mutating operations. Useful for read-only configuration values.
Parameters
- $key : string
-
The key to protect from modification.
Tags
pruneLog()
Manually prunes the operation log to keep only recent entries.
public
pruneLog([int $keep = 100 ]) : void
Removes older log entries while keeping the specified number of recent ones. The pruning operation itself is logged.
Parameters
- $keep : int = 100
-
The number of recent log entries to preserve.
Tags
pull()
Retrieves and removes a key from the container in one operation.
public
pull(string $key[, mixed $default = null ]) : mixed
Atomically gets a value and removes it from the container, useful for one-time tokens or queue-like operations.
Parameters
- $key : string
-
The key to retrieve and remove.
- $default : mixed = null
-
The value to return if the key doesn't exist.
Tags
Return values
mixed —The retrieved value, or the default if not found.
purgeExpired()
Removes all expired TTL entries from the container.
public
purgeExpired() : void
Manually triggers cleanup of expired entries without waiting for individual key access. Useful for proactive memory management.
Tags
remember()
Returns a value if it exists, otherwise sets and returns the provided default.
public
remember(string $key, mixed $default) : mixed
Implements a "get or set" pattern, useful for lazy initialization or ensuring a key always has a value.
Parameters
- $key : string
-
The key to check and potentially set.
- $default : mixed
-
The value to set and return if the key doesn't exist.
Tags
Return values
mixed —The existing value or the newly set default.
removeContainer()
Completely removes a container and all associated metadata.
public
static removeContainer(string $name) : void
Deletes the container data, object instance, locks, protections, and dirty flags. The operation is logged before removal.
Parameters
- $name : string
-
The container name to remove.
Tags
removeFromSafe()
Removes all Cargo data from the Safe session system.
public
static removeFromSafe() : void
Cleans up Safe session storage by removing the Cargo instances data. Automatically ensures Safe is started before removing.
Tags
restore()
Restores the container to a previously saved snapshot version.
public
restore(string $versionName) : bool
Replaces all current container data with the data from the specified snapshot version. Respects container locks.
Parameters
- $versionName : string
-
The name of the snapshot version to restore.
Tags
Return values
bool —True if the restore was successful, false if version not found or container locked.
saveToFile()
Saves the container data to a JSON file.
public
saveToFile(string $filepath) : bool
Serializes the container to JSON and writes it to the specified file path. Useful for persistence between requests or application restarts.
Parameters
- $filepath : string
-
The file path to save the JSON data to.
Tags
Return values
bool —True if the file was written successfully, false otherwise.
saveToSafe()
Saves all container instances to the Safe session system.
public
static saveToSafe() : void
Stores the entire Cargo state in the Safe session for secure persistence across requests. Automatically ensures Safe is started before saving.
Tags
saveToSession()
Saves all container instances to the PHP session.
public
static saveToSession() : void
Stores the entire Cargo state in the session for persistence across requests. Automatically starts the session if not already active.
Tags
set()
Stores a value in the container with optional TTL expiration.
public
set(string $key, mixed $value[, int $ttl = 0 ]) : void
Values can be stored with an optional time-to-live (TTL) in seconds. TTL values are automatically checked and expired during retrieval.
Parameters
- $key : string
-
The storage key.
- $value : mixed
-
The value to store.
- $ttl : int = 0
-
Time-to-live in seconds. 0 means no expiration.
Tags
setDirty()
Manually sets the dirty flag for this container.
public
setDirty([bool $isDirty = true ]) : void
Allows manual control over the dirty state, useful for custom persistence logic or when loading data from external sources.
Parameters
- $isDirty : bool = true
-
The dirty state to set. Defaults to true.
Tags
setLogLimit()
Sets the global limit for log entries per container.
public
static setLogLimit(int $limit) : void
Parameters
- $limit : int
-
The maximum number of log entries to keep. Minimum is 0.
Tags
shouldReturnEmptyStringForNull()
Checks if this container instance is configured to return empty strings for null defaults.
public
shouldReturnEmptyStringForNull() : bool
Tags
Return values
bool —True if null-to-empty-string conversion is enabled for this instance.
shouldReturnEmptyStringsGlobally()
Checks if the global null-to-empty-string fallback is enabled.
public
static shouldReturnEmptyStringsGlobally() : bool
Tags
Return values
bool —True if new containers will default to null-to-empty-string conversion.
snapshot()
Creates a versioned snapshot of the current container state.
public
snapshot([string|null $versionName = null ]) : string
Captures the entire container data at a point in time for later restoration. If no version name is provided, uses a timestamp.
Parameters
- $versionName : string|null = null
-
Optional name for the snapshot. Auto-generated if null.
Tags
Return values
string —The name of the created snapshot version.
toJSON()
Serializes the container data to a JSON string.
public
toJSON([int $flags = 0 ]) : string
Converts all container data to JSON format for persistence, debugging, or API responses.
Parameters
- $flags : int = 0
-
JSON encoding flags (e.g., JSON_PRETTY_PRINT).
Tags
Return values
string —The container data as a JSON string.
__construct()
Initializes a new Cargo container instance with the specified name.
private
__construct(string $name) : mixed
This constructor is private to enforce the singleton pattern for named containers.
Use getInstance()
to obtain container instances.
Parameters
- $name : string
-
The unique name identifier for this container.
logStatic()
Static method for logging operations on named containers.
private
static logStatic(string $name, string $action[, string $key = '' ][, mixed $value = null ]) : void
Internal method used by the logging system to record operations with automatic pruning when the log limit is exceeded.
Parameters
- $name : string
-
The container name.
- $action : string
-
The action being performed.
- $key : string = ''
-
The key involved in the operation.
- $value : mixed = null
-
The value involved in the operation.
Tags
resolveDefault()
Resolves default values with null-to-empty-string conversion if enabled.
private
resolveDefault(mixed $default) : mixed
Internal method that handles the conversion of null defaults to empty strings when the feature is enabled for this container instance.
Parameters
- $default : mixed
-
The default value to potentially convert.
Return values
mixed —The default value, or empty string if null and conversion is enabled.