SysvSharedMemoryManager
in package
Final class that manages shared memory operations for Sysv IPC implementation
This class provides a comprehensive set of methods for managing shared memory segments in System V IPC environment. It handles key derivation, memory allocation, data storage/retrieval, and cleanup operations while maintaining thread safety through proper locking mechanisms.
The manager supports various data types through serialization, TTL-based expiration, and provides both synchronous and asynchronous access patterns. It's designed to be a robust foundation for inter-process communication in PHP applications.
Key features include:
- Automatic slot management for memory allocation
- Time-to-live (TTL) based expiration with automatic cleanup
- Thread/process safety through Sysv semaphores
- Error handling and exception management
- Namespace isolation for multiple IPC instances
- Memory efficiency through smart slot reuse
Tags
Table of Contents
Constants
- META_KEY : mixed = 1
Properties
- $baseKey : int
- $defaultTtl : int
- $lock : SysvSemaphoreManager
- $namespace : string
- $permissions : int
- $shm : SysvSharedMemory
- $shmSize : int
Methods
- __construct() : mixed
- Initializes a new SysvIpc instance for shared memory operations
- all() : array<string|int, mixed>
- Retrieves all key-value pairs from shared memory
- clear() : void
- Clears all entries from shared memory
- clearExpired() : int
- Clears all expired entries from shared memory
- count() : int
- Counts the number of items in storage
- decrement() : int
- Decrements a numeric value in shared memory
- delete() : bool
- Deletes a key from shared memory
- destroy() : void
- Destroys the shared memory segment
- detach() : void
- Detaches from the shared memory segment
- get() : mixed
- Retrieves a value from shared memory by key with default fallback
- getNativeSharedMemory() : SysvSharedMemory
- Retrieves the underlying SysvSharedMemory resource
- has() : bool
- Checks if a key exists in shared memory and is not expired
- increment() : int
- Increments a numeric value in shared memory
- keys() : array<string|int, mixed>
- Returns all keys from the storage
- pop() : mixed
- Removes and returns the last element from an array in shared memory
- pull() : mixed
- Retrieves and removes a key from shared memory
- push() : void
- Adds an element to the end of an array in shared memory
- remember() : mixed
- Retrieves a value from shared memory or sets it using a callback if not present
- set() : mixed
- Retrieves a value from shared memory by key with default fallback
- shift() : mixed
- Removes and returns the first element from an array in shared memory
- touch() : bool
- Updates the expiration time for a key in shared memory
- unshift() : void
- Adds an element to the beginning of an array in shared memory
- withLock() : mixed
- Executes a callback function with exclusive access to shared memory
- cleanupExpiredLocked() : int
- Cleans up expired entries from shared memory
- deleteUnlocked() : bool
- Deletes an entry from shared memory
- ensureMeta() : void
- Ensures that metadata exists in shared memory
- existsUnlocked() : bool
- Checks if an entry exists in shared memory
- getUnlocked() : mixed
- Gets a value from shared memory
- loadMetaUnlocked() : array<string|int, mixed>
- Loads metadata from shared memory (unlocked version)
- resolveSlot() : int
- Resolves the shared memory slot for a key
- saveMetaUnlocked() : void
- Saves metadata to the shared memory
Constants
META_KEY
private
mixed
META_KEY
= 1
Properties
$baseKey
private
int
$baseKey
$defaultTtl
private
int
$defaultTtl
= 3600
$lock
private
SysvSemaphoreManager
$lock
$namespace
private
string
$namespace
= 'sysv-ipc'
$permissions
private
int
$permissions
= 0666
$shm
private
SysvSharedMemory
$shm
$shmSize
private
int
$shmSize
= 1048576
Methods
__construct()
Initializes a new SysvIpc instance for shared memory operations
public
__construct(int $baseKey[, int $permissions = 0666 ][, int $shmSize = 1048576 ][, int $defaultTtl = 3600 ][, string $namespace = 'sysv-ipc' ]) : mixed
This constructor sets up the shared memory segment and associated metadata for inter-process communication. It performs necessary validations and initializes the underlying shared memory resources.
Parameters
- $baseKey : int
-
Base key for identifying this shared memory segment
- $permissions : int = 0666
-
Permissions for creating the shared memory segment (default: 0666)
- $shmSize : int = 1048576
-
Size of the shared memory segment in bytes (default: 1048576 = 1MB)
- $defaultTtl : int = 3600
-
Default time-to-live for stored items in seconds (default: 3600 = 1 hour)
- $namespace : string = 'sysv-ipc'
-
Namespace identifier for this IPC instance (default: 'sysv-ipc')
Tags
all()
Retrieves all key-value pairs from shared memory
public
all() : array<string|int, mixed>
This method returns an associative array of all key-value pairs stored in shared memory. It also cleans up expired entries during the process and ensures thread safety.
Return values
array<string|int, mixed> —All key-value pairs in shared memory
clear()
Clears all entries from shared memory
public
clear() : void
This method removes all entries from shared memory and clears the metadata. It ensures thread safety by using a locking mechanism during the operation.
clearExpired()
Clears all expired entries from shared memory
public
clearExpired() : int
This method removes all expired entries from shared memory and returns the count of how many entries were removed. It uses a locking mechanism to ensure thread safety during the operation.
Return values
int —Number of expired entries removed
count()
Counts the number of items in storage
public
count() : int
This method returns the total count of items by counting the keys available in the storage system.
Return values
int —Number of items in storage
decrement()
Decrements a numeric value in shared memory
public
decrement(string $key[, int $by = 1 ][, int|null $ttl = null ]) : int
This method decrements the value associated with the given key by the specified amount. It reuses the increment logic by passing a negative value to decrement.
Parameters
- $key : string
-
The key to decrement
- $by : int = 1
-
The amount to decrement by (default: 1)
- $ttl : int|null = null
-
Time-to-live for the key in seconds
Return values
int —The new decremented value
delete()
Deletes a key from shared memory
public
delete(string $key) : bool
This method removes a key and its associated value from shared memory. It is thread-safe and uses locking to ensure consistency during the operation. The method properly handles metadata cleanup after deletion.
Parameters
- $key : string
-
The key to delete
Return values
bool —True if the key was deleted, false if it didn't exist
destroy()
Destroys the shared memory segment
public
destroy() : void
This method clears all data from shared memory and removes the shared memory segment from the system. It also detaches from the memory segment.
detach()
Detaches from the shared memory segment
public
detach() : void
This method detaches the current process from the shared memory segment. It should be called when no longer using the shared memory.
get()
Retrieves a value from shared memory by key with default fallback
public
get(string $key[, mixed $default = null ]) : mixed
This method retrieves the value associated with a key from shared memory. It performs comprehensive validation including checking if the key exists, hasn't expired, and the underlying data is valid. If any of these checks fail, it cleans up the invalid entry and returns the default value.
Parameters
- $key : string
-
The key to retrieve value for
- $default : mixed = null
-
The default value to return if key doesn't exist or is invalid
Return values
mixed —The value from shared memory or the default value
getNativeSharedMemory()
Retrieves the underlying SysvSharedMemory resource
public
getNativeSharedMemory() : SysvSharedMemory
This method provides direct access to the SysvSharedMemory object, allowing direct manipulation of the shared memory segment when necessary. It's typically used internally by other methods that need to interact directly with the underlying shared memory mechanism.
Return values
SysvSharedMemory —The underlying shared memory resource
has()
Checks if a key exists in shared memory and is not expired
public
has(string $key) : bool
This method determines whether a key exists in shared memory and has not yet expired. It performs automatic cleanup by removing expired entries during the check. The method is thread-safe and uses locking to ensure consistency.
Parameters
- $key : string
-
The key to check for existence
Return values
bool —True if the key exists and is valid, false otherwise
increment()
Increments a numeric value in shared memory
public
increment(string $key[, int $by = 1 ][, int|null $ttl = null ]) : int
This method increments the value associated with the given key by the specified amount. It ensures thread safety by using locking during the operation. The method validates that the current value is numeric before performing the increment operation.
Parameters
- $key : string
-
The key to increment
- $by : int = 1
-
The amount to increment by (default: 1)
- $ttl : int|null = null
-
Time-to-live for the key in seconds
Tags
Return values
int —The new incremented value
keys()
Returns all keys from the storage
public
keys() : array<string|int, mixed>
This method retrieves all keys currently stored in the system by getting all available keys from the underlying data structure.
Return values
array<string|int, mixed> —Array of all keys
pop()
Removes and returns the last element from an array in shared memory
public
pop(string $key) : mixed
This method removes and returns the last element of an array stored at the specified key. It ensures thread safety by using locking during the operation.
Parameters
- $key : string
-
The key containing the array
Return values
mixed —The removed value or null if array is empty
pull()
Retrieves and removes a key from shared memory
public
pull(string $key[, mixed $default = null ]) : mixed
This method retrieves the value associated with a key and then deletes the key. It's useful for implementing "get and delete" operations atomically. The method is thread-safe and uses locking to ensure consistency.
Parameters
- $key : string
-
The key to retrieve and remove
- $default : mixed = null
-
Default value to return if key doesn't exist
Return values
mixed —The value of the key or default if not found
push()
Adds an element to the end of an array in shared memory
public
push(string $key, mixed $value[, int|null $ttl = null ]) : void
This method appends a value to the end of an array stored at the specified key. It ensures thread safety by using locking during the operation.
Parameters
- $key : string
-
The key containing the array
- $value : mixed
-
The value to add to the array
- $ttl : int|null = null
-
Time-to-live for the key in seconds
Tags
remember()
Retrieves a value from shared memory or sets it using a callback if not present
public
remember(string $key, callable $callback[, int|null $ttl = null ]) : mixed
This method checks if a key exists in shared memory and returns its value if found. If the key doesn't exist, it executes the provided callback to generate a value, stores it in shared memory, and returns it. It ensures thread safety by using locking.
Parameters
- $key : string
-
The key to check or set
- $callback : callable
-
Callback that generates a value if key is not found
- $ttl : int|null = null
-
Time-to-live for the key in seconds
Return values
mixed —The value from shared memory or the result of the callback
set()
Retrieves a value from shared memory by key with default fallback
public
set(string $key, mixed $value[, int|null $ttl = null ]) : mixed
This method retrieves the value associated with a key from shared memory. It performs comprehensive validation including checking if the key exists, hasn't expired, and the underlying data is valid. If any of these checks fail, it cleans up the invalid entry and returns the default value.
Parameters
- $key : string
-
The key to retrieve value for
- $value : mixed
- $ttl : int|null = null
Return values
mixed —The value from shared memory or the default value
shift()
Removes and returns the first element from an array in shared memory
public
shift(string $key) : mixed
This method removes and returns the first element of an array stored at the specified key. It ensures thread safety by using locking during the operation.
Parameters
- $key : string
-
The key containing the array
Return values
mixed —The removed value or null if array is empty
touch()
Updates the expiration time for a key in shared memory
public
touch(string $key[, int|null $ttl = null ]) : bool
This method extends the lifetime of an existing key by updating its expiration time. It refreshes the TTL (time-to-live) for the specified key, pushing back its expiration. If the key doesn't exist or becomes invalid during the operation, it returns false.
Parameters
- $key : string
-
The key to touch (update)
- $ttl : int|null = null
-
Time-to-live in seconds, or null to use default TTL
Return values
bool —True if the key was successfully touched, false otherwise
unshift()
Adds an element to the beginning of an array in shared memory
public
unshift(string $key, mixed $value[, int|null $ttl = null ]) : void
This method prepends a value to the beginning of an array stored at the specified key. It ensures thread safety by using locking during the operation.
Parameters
- $key : string
-
The key containing the array
- $value : mixed
-
The value to add to the beginning of the array
- $ttl : int|null = null
-
Time-to-live for the key in seconds
Tags
withLock()
Executes a callback function with exclusive access to shared memory
public
withLock(callable $callback[, bool $nowait = false ]) : mixed
This method ensures thread safety by acquiring an exclusive lock before executing the provided callback and releasing it afterward. It can operate in blocking or non-blocking mode depending on the nowait parameter.
Parameters
- $callback : callable
-
The function to execute within the lock
- $nowait : bool = false
-
If true, don't block when acquiring the lock
Return values
mixed —The result of the callback function
cleanupExpiredLocked()
Cleans up expired entries from shared memory
private
cleanupExpiredLocked(array<string|int, mixed> &$meta) : int
This function iterates through all entries in shared memory and removes expired items. It also cleans up the associated data for those entries.
Parameters
- $meta : array<string|int, mixed>
-
Array of metadata to check
Return values
int —Number of expired items removed
deleteUnlocked()
Deletes an entry from shared memory
private
deleteUnlocked(string $key, array<string|int, mixed> &$meta) : bool
This function removes a specified key from shared memory and the associated data. It also updates the metadata array by removing information about this entry.
Parameters
- $key : string
-
Key to delete
- $meta : array<string|int, mixed>
-
Metadata array to update
Return values
bool —true if operation succeeded, false otherwise
ensureMeta()
Ensures that metadata exists in shared memory
private
ensureMeta() : void
This private method checks if metadata exists in shared memory and creates it with default values if it doesn't exist yet.
existsUnlocked()
Checks if an entry exists in shared memory
private
existsUnlocked(string $key, array<string|int, mixed> $meta) : bool
This function checks whether a specified key exists in shared memory and is not expired.
Parameters
- $key : string
-
Key to check
- $meta : array<string|int, mixed>
-
Metadata array
Return values
bool —true if entry exists and is not expired, false otherwise
getUnlocked()
Gets a value from shared memory
private
getUnlocked(string $key, array<string|int, mixed> &$meta[, mixed $default = null ]) : mixed
This function retrieves the value for a given key from shared memory. If the entry is expired or doesn't exist, it may return a default value.
Parameters
- $key : string
-
Key to retrieve
- $meta : array<string|int, mixed>
-
Metadata array
- $default : mixed = null
-
Default value to return if entry doesn't exist
Return values
mixed —Value for the given key or default value
loadMetaUnlocked()
Loads metadata from shared memory (unlocked version)
private
loadMetaUnlocked() : array<string|int, mixed>
This private method retrieves metadata from shared memory. If metadata doesn't exist or is invalid, it returns default empty structure.
Return values
array<string|int, mixed> —Metadata loaded from shared memory
resolveSlot()
Resolves the shared memory slot for a key
private
resolveSlot(string $key, array<string|int, mixed> $meta) : int
This function generates or assigns a shared memory slot number for a given key. It uses collision detection mechanisms to avoid slot conflicts.
Parameters
- $key : string
-
Key to resolve slot for
- $meta : array<string|int, mixed>
-
Metadata array containing information about existing entries
Return values
int —Shared memory slot number
saveMetaUnlocked()
Saves metadata to the shared memory
private
saveMetaUnlocked(array<string|int, mixed> $meta) : void
This function stores an array of metadata into the system's shared memory using the specified shared memory identifier.
Parameters
- $meta : array<string|int, mixed>
-
Array of metadata to save