Primordyx Framework Documentation

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 helpersset(), get(), has(), forget(), flush(). TTL support – store temp data that auto‑expires ($ttl in seconds). Lazy valueslazy($key, fn() => heavy()) only runs the callback once. Snapshots / restoresnapshot() versions the whole container; restore() rolls back. Diff & merge – static helpers compare or merge two containers. Protection & lgProtect 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
example
$cargo = \Primordyx\Cargo::getInstance();          // default container
$cargo->set('user_id', 42);

$config = \Primordyx\Cargo::getInstance('whatever'); // separate container
$config->remember('db', fn() => new PDO(...));
since
1.0.0

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 = []

$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
example
$cargo->addToArray('users', 'john');
$cargo->addToArray('users', 'jane');
$users = $cargo->get('users'); // ['john', 'jane']
note

If the key contains a non-array value, it will be replaced with a new array.

all()

Alias for dump() - returns all container data.

public all() : array<string|int, mixed>
Tags
see
dump()
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
example
$all = Cargo::allInstances();
// ['default' => [...], 'session' => [...], 'cache' => [...]]
note

This returns the actual data arrays, not the Cargo object instances.

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
example
Cargo::clearFromSession();  // Remove all Cargo data from session

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
example
Cargo::copy('production_config', 'backup_config');
note

If the source container doesn't exist, no operation is performed.

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
example
$diff = Cargo::diff('original', 'modified');
// ['added' => [...], 'removed' => [...], 'changed' => [...]]
note

Non-existent containers are treated as empty arrays.

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
example
$data = $cargo->dump();
foreach ($data as $key => $value) {
    echo "$key => " . print_r($value, true);
}
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
example
if (Cargo::exists('session')) {
    $session = Cargo::getInstance('session');
}
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
example
$cargo->flush(); // Remove all keys and values
note

Operations on locked containers are silently ignored and logged.

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
example
$cargo->forget('temp_data');  // Remove the key completely
note

Operations on locked containers or protected keys are silently ignored and logged.

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
example
Cargo::forgetAll(); // Clean slate for testing or reset
note

This is a destructive operation that cannot be undone.

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
example
$userId = $cargo->get('user_id', 0);        // Returns 0 if not set
$config = $cargo->get('app_config', []);    // Returns empty array if not set
note

Expired TTL entries are automatically removed and logged during retrieval.

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
example
$expires = $cargo->getExpiresAt('temp_token');
if ($expires && $expires < time() + 60) {
    // Token expires in less than 1 minute
}
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
example
$default = Cargo::getInstance();           // Gets 'default' container
$session = Cargo::getInstance('session');  // Gets 'session' container
$cache = Cargo::getInstance('cache');      // Gets 'cache' container
note

Each named container maintains its own separate data store and configuration.

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
example
$allLogs = $cargo->getLog();                    // All operations
$setLogs = $cargo->getLog('set');               // Only 'set' operations
$blockedLogs = $cargo->getLog('blocked:');      // Only blocked operations
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
example
$currentLimit = Cargo::getLogLimit();
Return values
int

The maximum number of log entries kept per container.

getName()

Gets the name of this container instance.

public getName() : string
Tags
example

$cargo = Cargo::getInstance('session'); echo $cargo->getName(); // 'session'

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
example
if ($cargo->has('user_session')) {
    $session = $cargo->get('user_session');
}
note

Expired TTL entries are automatically removed during this check.

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
example
$cargo = Cargo::getInstance();
echo $cargo->isDirty(); // false
$cargo->set('key', 'value');
echo $cargo->isDirty(); // true
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
example
if (!$cargo->isLocked()) {
    $cargo->set('safe_to_write', true);
}
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
example
if (!$cargo->isProtected('user_data')) {
    $cargo->set('user_data', $newData);
}
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
example
$keys = $cargo->keys(); // ['user_id', 'session_data', 'preferences']
foreach ($keys as $key) {
    echo "Key: $key, Value: " . $cargo->get($key) . "\n";
}
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
example
$config = $cargo->lazy('database_config', function() {
    return loadExpensiveDatabaseConfig();
});
note

The callback is only executed once per key, subsequent calls return the cached value.

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
example
$versions = $cargo->listVersions();
foreach ($versions as $version) {
    echo "Available version: $version\n";
}
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
example
$cargo->loadFromArray(['key1' => 'value1', 'key2' => 'value2']);
note

This operation resets the dirty flag to false after loading.

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
example
if ($cargo->loadFromFile('/tmp/cargo_backup.json')) {
    echo "Container loaded successfully";
}
note

Returns false if the file doesn't exist or contains invalid JSON.

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
example
Cargo::loadFromSafe();  // Restore containers from Safe session
note

All loaded containers have their dirty flags reset to false.

throws
Exception

If Safe session cannot be started.

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
example
Cargo::loadFromSession();  // Restore containers from session
note

All loaded containers have their dirty flags reset to false.

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
example
$cargo->lock();
$cargo->set('key', 'value'); // Silently ignored and logged
note

Once locked, a container cannot be unlocked within the same request.

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
example
$cargo->log('custom_action', 'user_id', 42);
note

Logs are automatically pruned when they exceed the global limit.

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
example
Cargo::merge('default_config', 'user_config', false); // Keep user settings
Cargo::merge('new_data', 'existing_data', true);      // Overwrite existing
note

Creates the destination container if it doesn't exist.

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
example
$cargo->mergeArray(['new_key' => 'value'], true);  // Overwrite existing
$cargo->mergeArray(['safe_key' => 'value'], false); // Keep existing
note

Protected keys and locked containers prevent merging with appropriate logging.

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
example
$cargo->nullsAreEmptyStrings(true);           // For this container only
$cargo->nullsAreEmptyStrings(true, true);     // For all new containers
$value = $cargo->get('missing_key');          // Returns '' instead of null
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
example
$temp = Cargo::on('temporary');    // Creates new instance each call
$temp2 = Cargo::on('temporary');   // Different instance than $temp
note

These instances are not globally shared and won't appear in allInstances().

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
example
$cargo->set('config', ['db_host' => 'localhost']);
$cargo->protect('config');
$cargo->set('config', 'new_value'); // Silently ignored and logged

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
example
$cargo->pruneLog(50);  // Keep only the last 50 log entries
note

The pruning operation is logged with statistics about removed entries.

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
example
$token = $cargo->pull('csrf_token', null);  // Get and remove token
$message = $cargo->pull('flash_message', ''); // Get and remove message
note

Both the retrieval and removal are logged separately.

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
example
$cargo->purgeExpired(); // Clean up all expired entries
note

Each purged entry is logged and the container is marked as dirty.

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
example
$config = $cargo->remember('app_config', ['debug' => false]);
$counter = $cargo->remember('page_views', 0);
note

If the key exists, the default value is not stored or returned.

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
example
Cargo::removeContainer('temporary_data');
note

Logs are preserved even after container removal.

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
example
Cargo::removeFromSafe();  // Remove all Cargo data from Safe session
throws
Exception

If Safe session cannot be started.

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
example
$cargo->restore('initial_state');
$cargo->restore('before_user_changes');
note

Locked containers cannot be restored.

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
throws
Exception

If JSON encoding fails.

example
if ($cargo->saveToFile('/tmp/cargo_backup.json')) {
    echo "Container saved successfully";
}
note

The file is created with JSON_PRETTY_PRINT for readability.

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
throws
Exception

If Safe session cannot be started or data cannot be saved.

example
Cargo::saveToSafe();  // Persist all containers to Safe session
note

Objects will lose class information due to JSON serialization. Use only JSON-compatible data (primitives, arrays, JsonSerializable objects).

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
example
Cargo::saveToSession();  // Persist all containers to session
note

Only primitive values and arrays should be stored to avoid serialization issues.

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
example
$cargo->set('user_id', 42);           // Permanent storage
$cargo->set('temp_token', 'abc123', 300); // Expires in 5 minutes
note

Operations on locked containers or protected keys are silently ignored and logged.

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
example
$cargo->setDirty(false);  // Mark as clean after saving
$cargo->setDirty(true);   // Force dirty state

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
example
Cargo::setLogLimit(500);  // Keep last 500 log entries
Cargo::setLogLimit(0);    // Disable logging

shouldReturnEmptyStringForNull()

Checks if this container instance is configured to return empty strings for null defaults.

public shouldReturnEmptyStringForNull() : bool
Tags
example
if ($cargo->shouldReturnEmptyStringForNull()) {
    echo "This container converts nulls to empty strings";
}
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
example
if (Cargo::shouldReturnEmptyStringsGlobally()) {
    echo "New containers will convert nulls to empty strings";
}
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
example
$version = $cargo->snapshot('before_changes');
// Make changes...
$cargo->restore('before_changes'); // Rollback
note

Snapshots persist until the container is removed or the application restarts.

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
throws
Exception

If JSON encoding fails.

example
$json = $cargo->toJSON(JSON_PRETTY_PRINT);
file_put_contents('cargo_backup.json', $json);
note

TTL metadata is included in the JSON output.

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
note

This method handles automatic log pruning and adds pruning entries.

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.


        
On this page

Search results