silviooosilva/cacheer-php
Composer 安装命令:
composer require silviooosilva/cacheer-php
包简介
CacheerPHP is a minimalist package for caching in PHP, offering a simple interface for storing and retrieving cached data using multiple backends.
关键字:
README 文档
README
A modern, fluent PHP caching library with multiple backends, PSR compliance, encryption and zero framework dependencies.
Why CacheerPHP?
Most PHP caching solutions are either too minimal or buried inside a framework. CacheerPHP gives you a complete caching toolkit that works anywhere — from a small script to a full application — with a clean, fluent API and no framework lock-in.
- 4 storage drivers — File, Database (MySQL/PostgreSQL/SQLite), Redis and in-memory Array
- PSR-16 & PSR-3 — Standards-compliant SimpleCache adapter and logger out of the box
- AES-256-CBC encryption — Protect sensitive cached data with a single method call
- Gzip compression — Reduce storage footprint automatically
- Fluent OptionBuilder — Type-safe, IDE-friendly configuration with zero typos
- Tags & namespaces — Group and invalidate related entries effortlessly
- Human-readable TTL — Write
"2 hours"instead of7200 - Static & instance API — Use whichever style fits your codebase
- 150+ tests — Battle-tested with PHPUnit
Quick Start
composer require silviooosilva/cacheer-php
use Silviooosilva\CacheerPhp\Cacheer; $cache = new Cacheer(['cacheDir' => __DIR__ . '/cache']); $cache->setDriver()->useFileDriver(); // Write $cache->putCache('user:1', ['id' => 1, 'name' => 'John']); // Read $user = $cache->getCache('user:1'); // Check if ($cache->has('user:1')) { echo "Cache hit!"; }
That's it — you're caching. Keep reading for the good stuff.
Table of Contents
- Drivers
- Configuration
- OptionBuilder
- Encryption & Compression
- Tags & Namespaces
- PSR-16 SimpleCache
- Formatter
- API Reference
- Testing
- Documentation
- Contributing
- License
Drivers
Switch between backends with a single call:
$cache->setDriver()->useFileDriver(); // Filesystem $cache->setDriver()->useDatabaseDriver(); // MySQL, PostgreSQL, SQLite $cache->setDriver()->useRedisDriver(); // Redis $cache->setDriver()->useArrayDriver(); // In-memory (great for tests)
| Feature | File | Database | Redis | Array |
|---|---|---|---|---|
| Persistence | Disk | DB | Server | No |
| Tags | Yes | Yes | Yes | Yes |
| Namespaces | Yes | Yes | Yes | Yes |
| Compression | Yes | Yes | Yes | Yes |
| Encryption | Yes | Yes | Yes | Yes |
| Auto-flush | Yes | Yes | Yes | - |
| Best for | Single server | Shared state | High throughput | Testing |
Configuration
Environment variables
Copy the example file and adjust:
cp .env.example .env
# SQLite (default) DB_CONNECTION=sqlite # MySQL / PostgreSQL DB_CONNECTION=mysql DB_HOST=127.0.0.1 DB_PORT=3306 DB_DATABASE=cacheer_db DB_USERNAME=root DB_PASSWORD=secret # Redis REDIS_HOST=127.0.0.1 REDIS_PORT=6379
Plain array
$cache = new Cacheer([ 'cacheDir' => __DIR__ . '/cache', 'loggerPath' => __DIR__ . '/logs/cacheer.log', 'expirationTime' => '1 hour', 'flushAfter' => '1 day', ]);
Static API
Cacheer::setConfig()->setTimeZone('UTC'); Cacheer::setDriver()->useArrayDriver(); Cacheer::putCache('key', 'value'); $value = Cacheer::getCache('key');
OptionBuilder
Forget string typos. The OptionBuilder gives you a fluent, type-safe way to configure each driver with full IDE autocompletion:
use Silviooosilva\CacheerPhp\Config\Option\Builder\OptionBuilder; $options = OptionBuilder::forFile() ->dir(__DIR__ . '/cache') ->loggerPath(__DIR__ . '/logs/cache.log') ->expirationTime('2 hours') ->flushAfter('1 day') ->build(); $cache = new Cacheer($options); $cache->setDriver()->useFileDriver();
Each driver has its own builder with driver-specific methods:
// Redis $options = OptionBuilder::forRedis() ->setNamespace('app:') ->loggerPath(__DIR__ . '/logs/cache.log') ->expirationTime('2 hours') ->flushAfter('1 day') ->build(); // Database $options = OptionBuilder::forDatabase() ->table('cache_items') ->loggerPath(__DIR__ . '/logs/cache.log') ->expirationTime('30 minutes') ->flushAfter('7 days') ->build();
The expirationTime() and flushAfter() methods also support the TimeBuilder fluent API:
$options = OptionBuilder::forFile() ->dir(__DIR__ . '/cache') ->expirationTime()->hour(2) ->flushAfter()->day(1) ->build();
Encryption & Compression
Encryption
Protect sensitive cached data with AES-256-CBC encryption. Each value gets a unique random IV — no two ciphertexts are alike, even for the same input.
$cache->useEncryption('your-secret-key-here'); $cache->putCache('token', 'sensitive-data'); // Stored encrypted, decrypted transparently on read $token = $cache->getCache('token'); // "sensitive-data"
Compression
Reduce storage size with gzip compression — useful for large cached payloads:
$cache->useCompression(); $cache->putCache('large-dataset', $hugeArray);
Both can be combined:
$cache->useCompression(); $cache->useEncryption('my-key'); // Data is compressed, then encrypted before storage $cache->putCache('secure-payload', $data);
Tags & Namespaces
Tags
Group related cache entries and invalidate them all at once:
$cache->putCache('user:1', $userData); $cache->putCache('user:2', $otherUser); $cache->tag('users', 'user:1', 'user:2'); // Later — flush everything tagged "users" $cache->flushTag('users');
Namespaces
Logically separate cache entries to avoid key collisions:
$cache->putCache('config', $appConfig, 'app'); $cache->putCache('config', $apiConfig, 'api'); $cache->getCache('config', 'app'); // $appConfig $cache->getCache('config', 'api'); // $apiConfig
PSR-16 SimpleCache
Need a standards-compliant interface? Wrap any Cacheer instance with the PSR-16 adapter:
use Silviooosilva\CacheerPhp\Psr\Psr16CacheAdapter; $cache = new Cacheer(['cacheDir' => __DIR__ . '/cache']); $cache->setDriver()->useFileDriver(); $psr16 = new Psr16CacheAdapter($cache); $psr16->set('key', 'value', 3600); $psr16->get('key'); // "value" $psr16->get('missing', 'default'); // "default" $psr16->delete('key'); $psr16->has('key'); // false // Batch operations $psr16->setMultiple(['a' => 1, 'b' => 2]); $psr16->getMultiple(['a', 'b', 'c'], 'default'); $psr16->deleteMultiple(['a', 'b']); $psr16->clear();
This adapter works with any library that accepts Psr\SimpleCache\CacheInterface.
Formatter
Transform cached data on retrieval with the built-in formatter:
$cache->useFormatter(); $json = $cache->getCache('user:1')->toJson(); // JSON string $array = $cache->getCache('user:1')->toArray(); // Array $object = $cache->getCache('user:1')->toObject(); // stdClass $string = $cache->getCache('user:1')->toString(); // String cast
API Reference
Write Operations
| Method | Returns | Description |
|---|---|---|
putCache($key, $data, $ns, $ttl) |
bool |
Store a value |
add($key, $data, $ns, $ttl) |
bool |
Store only if key doesn't exist |
putMany($items, $ns, $batch) |
bool |
Store multiple key-value pairs |
forever($key, $data) |
bool |
Store with no expiration |
appendCache($key, $data, $ns) |
bool |
Append to an existing value |
increment($key, $amount, $ns) |
bool |
Increment a numeric value |
decrement($key, $amount, $ns) |
bool |
Decrement a numeric value |
renewCache($key, $ttl, $ns) |
bool |
Refresh a key's TTL |
remember($key, $ttl, $fn) |
mixed |
Get or compute and store |
rememberForever($key, $fn) |
mixed |
Get or compute and store forever |
Read Operations
| Method | Returns | Description |
|---|---|---|
getCache($key, $ns) |
mixed |
Retrieve a cached value |
getMany($keys, $ns) |
array |
Retrieve multiple values |
getAll($ns) |
array |
Retrieve all values in namespace |
getAndForget($key, $ns) |
mixed |
Retrieve and delete (atomic pop) |
has($key, $ns) |
bool |
Check if a key exists |
Delete Operations
| Method | Returns | Description |
|---|---|---|
clearCache($key, $ns) |
bool |
Delete a single entry |
flushCache() |
bool |
Delete all entries |
tag($tag, ...$keys) |
bool |
Associate keys with a tag |
flushTag($tag) |
bool |
Delete all entries for a tag |
Configuration & State
| Method | Returns | Description |
|---|---|---|
setDriver() |
CacheDriver |
Switch storage backend |
setConfig() |
CacheConfig |
Access configuration |
useEncryption($key) |
Cacheer |
Enable AES-256 encryption |
useCompression($on) |
Cacheer |
Enable gzip compression |
useFormatter() |
void |
Enable output formatter |
getOption($key, $default) |
mixed |
Get a config option |
getOptions() |
array |
Get all config options |
setOption($key, $value) |
Cacheer |
Set a config option |
stats() |
array |
Driver, compression & encryption status |
isSuccess() |
bool |
Last operation succeeded? |
getMessage() |
string |
Human-readable status message |
TTL Formats
CacheerPHP accepts TTL in multiple formats:
$cache->putCache('key', 'value', '', 3600); // Seconds (int) $cache->putCache('key', 'value', '', '2 hours'); // Human-readable string $cache->putCache('key', 'value', '', new DateInterval('PT2H')); // DateInterval $cache->forever('key', 'value'); // No expiration
Requirements
- PHP 8.2+
ext-pdo— for database driversext-openssl— for encryptionext-zlib— for compression- Redis server — when using the Redis driver
Testing
composer install vendor/bin/pest
Documentation
Full documentation is available at CacheerPHP Documentation.
Contributing
Contributions are welcome! Please open an issue or submit a pull request.
License
CacheerPHP is open-sourced software licensed under the MIT license.
Support
If CacheerPHP saves you time, consider supporting the project:
silviooosilva/cacheer-php 适用场景与选型建议
silviooosilva/cacheer-php 是一款 基于 PHP 开发的 Composer 扩展包,目前已累计 106 次下载、GitHub Stars 达 31, 最近一次更新时间为 2024 年 07 月 18 日, 在 PHP 生态内属于活跃度较高的组件。
它主要适用于以下技术方向: 「nosql」 「redis」 「database」 「performance」 「php」 「cache」 等业务场景。在实际项目中,围绕这些方向常见需要落地的问题包括:接口对接、性能调优、并发安全、与既有框架(Laravel / ThinkPHP / Yii / Webman 等)的兼容适配,以及生产环境的日志埋点与稳定性保障。
我们在过去多个企业项目中使用过 silviooosilva/cacheer-php 或与其功能相近的方案,如果你在选型或落地过程中遇到问题,例如 版本兼容、二次改造、私有化封装、与内部系统对接、生产 BUG 排查,欢迎联系我们协助评估。
基于 silviooosilva/cacheer-php 在你已有业务上做功能扩展、字段裁剪、UI 适配、与内部账号 / 权限 / 日志系统的深度对接。
线上偶发问题、内存泄漏、慢查询、并发异常等排查修复;针对高流量场景做缓存、队列、索引层面的调优。
承接完整的项目从需求 → 设计 → 开发 → 上线 → 长期运维;也可按月提供技术保姆服务。
与 silviooosilva/cacheer-php 相关的其它包
同方向 / 同关键字的高下载量 PHP Composer 包推荐,方便对比选型:
Dibi is Database Abstraction Library for PHP
The DreamFactory(tm) CouchDB Service.
Microservice RPC through message queues.
Store your language lines in the database, yaml or other sources
The CodeIgniter Redis package
A package for automatically encrypting and decrypting Eloquent attributes in Laravel 5.5+, based on configuration settings.
统计信息
- 总下载量: 106
- 月度下载量: 0
- 日度下载量: 0
- 收藏数: 32
- 点击次数: 29
- 依赖项目数: 1
- 推荐数: 0
其他信息
- 授权协议: MIT
- 更新时间: 2024-07-18
