solophp/cache
Composer 安装命令:
composer require solophp/cache
包简介
PSR-16 compliant cache library with pluggable adapters
README 文档
README
A flexible, PSR-16 compliant cache library with pluggable adapters for PHP 8.1+.
Features
- Full PSR-16 (Simple Cache) compliance
- Pluggable adapter architecture
- File-based cache adapter
- Redis cache adapter
- Thread-safe file operations with
LOCK_EX - Automatic expiration handling
- Support for TTL as integer seconds or DateInterval
Installation
composer require solophp/cache
For Redis support, ensure you have the Redis PHP extension installed:
pecl install redis
Usage
File Cache
<?php use Solo\Cache\Cache; use Solo\Cache\Adapter\FileAdapter; // Create file adapter $adapter = new FileAdapter('/path/to/cache/directory'); // Create cache instance $cache = new Cache($adapter); // Store a value $cache->set('user.123', ['name' => 'John', 'email' => 'john@example.com'], 3600); // Retrieve a value $user = $cache->get('user.123'); // Check if key exists if ($cache->has('user.123')) { echo "Cache hit!"; } // Delete a key $cache->delete('user.123'); // Clear all cache $cache->clear();
Redis Cache
<?php use Solo\Cache\Cache; use Solo\Cache\Adapter\RedisAdapter; use Redis; // Create Redis connection $redis = new Redis(); $redis->connect('127.0.0.1', 6379); // Create Redis adapter (default MODE_THROW, prefix "cache:") $adapter = new RedisAdapter($redis); // Or with custom prefix and graceful error handling $adapter = new RedisAdapter($redis, RedisAdapter::MODE_FAIL, 'myapp:'); // Create cache instance $cache = new Cache($adapter); // Use the cache $cache->set('session.abc123', ['user_id' => 42], 7200); $session = $cache->get('session.abc123'); // Switch error mode at runtime if needed $adapter->setMode(RedisAdapter::MODE_FAIL);
Multiple Operations
<?php // Set multiple values $cache->setMultiple([ 'key1' => 'value1', 'key2' => 'value2', 'key3' => 'value3', ], 3600); // Get multiple values $values = $cache->getMultiple(['key1', 'key2', 'key3'], 'default'); // Delete multiple values $cache->deleteMultiple(['key1', 'key2']);
Using DateInterval for TTL
<?php use DateInterval; // Cache for 1 hour $cache->set('key', 'value', new DateInterval('PT1H')); // Cache for 1 day $cache->set('key', 'value', new DateInterval('P1D')); // Cache for 30 days $cache->set('key', 'value', new DateInterval('P30D'));
Adapters
FileAdapter
File-based cache implementation suitable for low to medium load applications.
Constructor Parameters:
$cacheDirectory(string): Directory path for storing cache files$mode(int): Error handling mode (optional, default: MODE_THROW)
Features:
- Two error handling modes:
FileAdapter::MODE_THROW- Throws exceptions on errors (default)FileAdapter::MODE_FAIL- Returns false/default on errors (graceful degradation)
- Optimized batch operations:
- Automatic deduplication of keys in batch operations
- Early return for empty arrays
- Graceful error handling in batch operations
- Garbage collection method
gc()for manual cleanup of expired files - Refactored cache loading with centralized
loadCacheData()method - Automatic directory creation with 0755 permissions
- Thread-safe operations with file locking (LOCK_EX)
- Automatic cleanup of expired entries on read operations
- Uses MD5 hashing for file names
- Runtime mode switching with
setMode()method
Usage with error modes:
// Default mode - throws exceptions $adapter = new FileAdapter('/path/to/cache'); // Graceful mode - returns defaults on errors $adapter = new FileAdapter('/path/to/cache', FileAdapter::MODE_FAIL); // Manual garbage collection $deletedFiles = $adapter->gc(); // Returns number of deleted expired files
Limitations:
- Not suitable for high-performance or distributed systems
- Consider Redis or Memcached for high-load scenarios
RedisAdapter
Redis-based cache implementation for high-performance and distributed applications.
Constructor Parameters:
$redis(Redis): Connected Redis instance$mode(int): Error handling mode (optional, default: MODE_THROW)$prefix(string): Key prefix for namespace isolation (optional, default:cache:)
Features:
- Optimized batch operations using Redis native commands (mGet, mSet, del)
getMultiple()uses single mGet call instead of N individual getssetMultiple()uses atomic mSet when no TTL is specifieddeleteMultiple()uses single del call with array of keys
- Manual serialization — correctly handles all PHP types including
false - Production-safe
clear()— uses SCAN instead of KEYS to avoid blocking Redis - Two error handling modes:
RedisAdapter::MODE_THROW- Throws exceptions on errors (default)RedisAdapter::MODE_FAIL- Returns false/default on errors (graceful degradation)
- Automatic deduplication of keys in batch operations
- Configurable key prefix for multi-app namespace isolation
- Native Redis TTL support
- Runtime mode switching with
setMode()method - Suitable for distributed systems
Key Validation
Both adapters enforce PSR-16 key requirements:
- Keys cannot be empty
- Only alphanumeric characters, underscores, dots, colons, and hyphens are allowed
- Pattern:
/^[a-zA-Z0-9_.:-]+$/ - Colons (
:) are supported as the standard separator for cache keys (Redis, Memcached conventions) - Hyphens (
-) are supported for UUID keys
Example keys:
user:123:profilecache:session:abc123app.config.database550e8400-e29b-41d4-a716-446655440000
Invalid keys will throw Solo\Cache\Exception\InvalidArgumentException.
Exceptions
The library provides PSR-16 compliant exceptions:
Solo\Cache\Exception\InvalidArgumentException- Invalid cache keys or argumentsSolo\Cache\Exception\CacheException- Cache operation failures
Requirements
- PHP 8.1 or higher
- psr/simple-cache ^3.0
- ext-redis (for Redis adapter)
License
MIT
solophp/cache 适用场景与选型建议
solophp/cache 是一款 基于 PHP 开发的 Composer 扩展包,目前已累计 23 次下载、GitHub Stars 达 0, 最近一次更新时间为 2025 年 10 月 22 日, 在 PHP 生态内属于活跃度较高的组件。
它主要适用于以下技术方向: 「redis」 「php」 「cache」 「storage」 「caching」 「adapter」 等业务场景。在实际项目中,围绕这些方向常见需要落地的问题包括:接口对接、性能调优、并发安全、与既有框架(Laravel / ThinkPHP / Yii / Webman 等)的兼容适配,以及生产环境的日志埋点与稳定性保障。
我们在过去多个企业项目中使用过 solophp/cache 或与其功能相近的方案,如果你在选型或落地过程中遇到问题,例如 版本兼容、二次改造、私有化封装、与内部系统对接、生产 BUG 排查,欢迎联系我们协助评估。
基于 solophp/cache 在你已有业务上做功能扩展、字段裁剪、UI 适配、与内部账号 / 权限 / 日志系统的深度对接。
线上偶发问题、内存泄漏、慢查询、并发异常等排查修复;针对高流量场景做缓存、队列、索引层面的调优。
承接完整的项目从需求 → 设计 → 开发 → 上线 → 长期运维;也可按月提供技术保姆服务。
与 solophp/cache 相关的其它包
同方向 / 同关键字的高下载量 PHP Composer 包推荐,方便对比选型:
repository php library
Microservice RPC through message queues.
The CodeIgniter Redis package
贝嘟分布式缓存扩展
Laravel 5 - Repositories to the database layer
Redis distributed locks for laravel
统计信息
- 总下载量: 23
- 月度下载量: 0
- 日度下载量: 0
- 收藏数: 0
- 点击次数: 9
- 依赖项目数: 0
- 推荐数: 0
其他信息
- 授权协议: MIT
- 更新时间: 2025-10-22