VOOZH about

URL: https://deepwiki.com/hypervel/cache/3.5-file-store

⇱ File Store | hypervel/cache | DeepWiki


Loading...
Menu

File Store

The File Store provides a filesystem-based cache implementation that persists cache entries as files on disk. This store is suitable for applications requiring cache persistence across restarts without external dependencies like Redis or database servers. The File Store supports atomic operations through file locking and implements both the core cache interface and distributed locking capabilities.

For information about other persistent storage options, see Database Store. For distributed caching solutions, see Redis Store. For lock implementation details, see Distributed Locking.

Overview

The FileStore class implements the Store and LockProvider interfaces, providing a complete cache solution backed by the filesystem. Each cache entry is stored as an individual file in a hashed directory structure, with the payload containing both expiration metadata and serialized data.

Key Characteristics:

  • Persistence: Data survives application restarts
  • Local-only: Not distributed across servers
  • File locking: Atomic operations via exclusive file locks
  • Directory sharding: Two-level hash-based directory structure
  • Permission management: Configurable file permissions for security

Sources: src/FileStore.php1-332

Class Structure


Sources: src/FileStore.php15-16 src/FileStore.php17-18 src/FileStore.php43-48

Directory Structure and File Organization

The File Store uses a two-level hashed directory structure to distribute cache files and prevent excessive files in a single directory. Each cache key is transformed into a SHA-1 hash, and the first four characters of the hash determine the directory path.

Directory Hierarchy Diagram


Path Generation Algorithm:

  1. Generate SHA-1 hash of the cache key
  2. Extract first 2 characters for level-1 directory
  3. Extract next 2 characters for level-2 directory
  4. Use full hash as filename

Sources: src/FileStore.php316-321

File Payload Format

Each cache file contains a structured payload with expiration metadata and serialized data. The format ensures efficient expiration checking without deserializing the entire payload.

Payload Structure

























ComponentSizeFormatPurpose
Expiration10 bytesZero-padded integerUNIX timestamp for expiration check
ValueVariablePHP serializedActual cached data

Expiration Timestamp Format:

  • 10-character string representation of UNIX timestamp
  • Zero-padded to exactly 10 characters
  • Special value 9999999999 represents "forever" (no expiration)
  • Example: 1704067200 for 2024-01-01 00:00:00 UTC

Sources: src/FileStore.php61-78 src/FileStore.php263-303 src/FileStore.php326-331

Core Cache Operations

Read Operation Flow


Sources: src/FileStore.php53-56 src/FileStore.php263-303

Write Operation Flow


Sources: src/FileStore.php61-78 src/FileStore.php234-245 src/FileStore.php250-258

Atomic Operations

The add() method provides atomic "add if not exists" functionality using exclusive file locks. This ensures race-condition-free cache initialization.

Atomic Add Operation


Sources: src/FileStore.php83-112

Increment and Decrement

The increment and decrement operations read the current value, modify it, and write it back with the remaining TTL preserved.

OperationMethodImplementation
Incrementincrement(string $key, int $value = 1)Reads payload, adds value, writes back with original TTL
Decrementdecrement(string $key, int $value = 1)Calls increment() with negative value

TTL Preservation: The payload includes time field representing remaining seconds until expiration. When incrementing, the store recalculates the expiration timestamp to maintain the original TTL.

Sources: src/FileStore.php117-132 src/FileStore.php297-302

Lock Integration

The File Store implements the LockProvider interface, enabling distributed locking using the filesystem as the coordination mechanism.

Lock Architecture


Lock Directory Configuration:

  • Default: Uses same directory as cache files
  • Configurable: Set separate directory via setLockDirectory()
  • Isolation: Separates lock files from data files when configured

Lock Implementation Details:

  • Each lock is a cache entry where key = lock name, value = owner identifier
  • Lock acquisition = atomic add() operation
  • Lock release = forget() operation
  • Lock ownership verification via owner identifier

Sources: src/FileStore.php145-163 src/FileStore.php216-221

Bulk Operations

Flush Operation

The flush() method removes all cached data by deleting all subdirectories within the cache directory.


Important Notes:

  • Only deletes first-level subdirectories (not individual files)
  • Relies on recursive directory deletion
  • Returns false if any subdirectory deletion fails
  • Returns false if cache directory doesn't exist

Sources: src/FileStore.php180-195

File Permissions

The File Store supports configurable file permissions for security and access control in shared hosting environments.

Permission Management

ComponentConfigurationDefault Behavior
Constructor parameter$filePermission (octal int)null (no explicit permissions)
Directory creationAlways 0777Modified by umask
File creationVia Filesystem::put()Modified by umask
Permission correctionAfter write operationsApplied if configured

Permission Enforcement Flow:

  1. Files/directories created with default permissions
  2. If $filePermission configured, ensurePermissionsAreCorrect() called
  3. Checks current permissions via chmod()
  4. Applies configured permissions if different
  5. Applied to both files and parent directories

Sources: src/FileStore.php38-48 src/FileStore.php234-245 src/FileStore.php250-258

Configuration and Initialization

Constructor Parameters































ParameterTypeRequiredPurpose
$filesFilesystemYesHyperf filesystem abstraction for file operations
$directorystringYesRoot directory for cache storage
$filePermissionint|nullNoOctal permissions for cache files/directories

Example Configuration:


Sources: src/FileStore.php43-48

Helper Methods

Key Methods Reference

MethodReturn TypeDescription
getFilesystem()FilesystemReturns the Filesystem instance
getDirectory()stringReturns the cache root directory path
setLockDirectory(?string $lockDirectory)staticConfigures separate lock directory
getPrefix()stringReturns empty string (no prefix support)

Note on Prefixing: Unlike other store implementations, FileStore returns an empty string for getPrefix(). Key prefixing is handled at the Repository layer, not the store level.

Sources: src/FileStore.php200-230

Error Handling

The File Store handles various error conditions gracefully:

Error ConditionHandling StrategyResult
File not found during readCaught exception in getPayload()Returns emptyPayload()
Expired cache fileAutomatic deletion via forget()Returns null
Deserialization failureCaught exception, file deletedReturns emptyPayload()
Lock timeout in add()Caught LockTimeoutExceptionReturns false
Write failureCheck bytes writtenReturns false
Directory creation failureException propagatesThrows exception

Automatic Cleanup: Expired entries are automatically deleted when accessed via get() or getPayload(), maintaining filesystem cleanliness without separate garbage collection.

Sources: src/FileStore.php263-303 src/FileStore.php83-112

Performance Considerations

Strengths

  • Local access: No network overhead
  • Simple implementation: Direct filesystem operations
  • Directory sharding: Prevents directory bloat
  • Lazy cleanup: Expired files removed on access
  • Lock support: Atomic operations via file locking

Limitations

  • Not distributed: Single server only
  • Filesystem I/O: Slower than memory-based stores
  • No bulk operations: getMany() performs individual reads
  • No native expiration: Relies on access-time cleanup
  • Lock contention: File locks can be slow under high concurrency

Recommended Use Cases:

  • Development environments
  • Single-server applications
  • Long-lived cache entries
  • Scenarios requiring cache persistence without external dependencies

Sources: src/FileStore.php1-332