coroq/with-cache
Composer 安装命令:
composer require coroq/with-cache
包简介
Simple, type-safe caching decorator trait
关键字:
README 文档
README
A trait for building type-safe caching wrappers.
Requirements
- PHP 8.0+
- PSR-6 cache implementation
Installation
composer require coroq/with-cache
Quick Start
Create a caching decorator class that wraps your original class. When a method is called, the result is cached. Subsequent calls with the same arguments return the cached result without calling the origin.
<?php use Coroq\Cache\WithCache; use Psr\Cache\CacheItemPoolInterface; // Your existing interface interface UserRepository { public function findById(int $id): ?User; } // Your existing implementation (no caching logic here) class DatabaseUserRepository implements UserRepository { public function findById(int $id): ?User { // fetch from database } } // Caching decorator - implements same interface class CachedUserRepository implements UserRepository { use WithCache; // this library public function __construct( UserRepository $origin, // the real repository CacheItemPoolInterface $cache, // PSR-6 cache pool ) { $this->setCacheOrigin($origin); $this->setCachePool($cache); } public function findById(int $id): ?User { // delegates to origin, caches the result return $this->withCache(); } } // Usage $repository = new CachedUserRepository( new DatabaseUserRepository($pdo), $cachePool, ); $user = $repository->findById(1); // calls database $user = $repository->findById(1); // returns cached result $user = $repository->findById(2); // different argument, calls database
Benefits
- Separation of concerns - The wrapper class adds caching around the original object. The original class can focus on pure business logic without any knowledge of caching.
- Respects types - The wrapper class implements the same interface as the original, with real methods and real type hints. IDE autocompletion works. Static analyzers like PHPStan understand your code. You can swap between cached and non-cached versions in your DI container.
Usage
Basic Caching
Each method that should be cached calls withCache():
class CachedProductService implements ProductService { use WithCache; public function __construct(ProductService $origin, CacheItemPoolInterface $cache) { $this->setCacheOrigin($origin); $this->setCachePool($cache); } public function getById(int $id): ?Product { return $this->withCache(); } public function getPopular(int $limit): array { return $this->withCache(); } }
Bypassing Cache
Use withoutCache() to skip caching for specific calls:
public function getById(int $id): ?Product { return $this->withoutCache(); // always calls origin }
Handling Cache Errors
Cache exceptions can be caught per-method:
use Psr\Cache\CacheException; public function getById(int $id): ?Product { try { return $this->withCache(); } catch (CacheException) { // fall back to origin on cache failure return $this->withoutCache(); } }
Custom TTL
By default, cached items have no expiration (live until the cache evicts them). Override getCacheTtl() to control expiration:
class CachedProductService implements ProductService { use WithCache; // ... protected function getCacheTtl(string $methodName, array $arguments, mixed $result): ?int { // return seconds, or null for no expiration return match($methodName) { 'getPopular' => 300, // 5 minutes 'getById' => 3600, // 1 hour default => null, }; } }
TTL can depend on the result:
protected function getCacheTtl(string $methodName, array $arguments, mixed $result): ?int { if ($result === null) { return 60; // cache "not found" briefly } return 3600; }
Custom Cache Key
Override makeCacheKey() to customize key generation:
protected function makeCacheKey(string $methodName, array $arguments): string { // default: sha1(class + method + serialized arguments) return "product.$methodName." . sha1(serialize($arguments)); }
Note: Arguments must be serializable. Closures, resources, and some anonymous classes cannot be used as arguments for cached methods.
Static Methods
Static methods cannot be cached with this trait. If the original class has static methods, implement them by calling the original directly:
public static function create(): self { return DatabaseUserRepository::create(); }
Cache Invalidation
The trait provides two protected methods for cache invalidation:
clearCache()- clears all cached items in the pooldeleteCacheItem(string $methodName, mixed ...$arguments)- deletes a specific cached result
Use these inside your cached class to invalidate stale entries:
class CachedUserRepository implements UserRepository { use WithCache; // ... public function findById(int $id): ?User { return $this->withCache(); } public function update(int $id, array $data): void { $this->withoutCache(); $this->deleteCacheItem('findById', $id); } public function importFromCsv(string $path): void { $this->withoutCache(); $this->clearCache(); // bulk operation, clear everything } }
Note: clearCache() calls clear() on the underlying cache pool. If you need isolated clearing per service, configure separate cache pools.
License
MIT
coroq/with-cache 适用场景与选型建议
coroq/with-cache 是一款 基于 PHP 开发的 Composer 扩展包,目前已累计 0 次下载、GitHub Stars 达 0, 最近一次更新时间为 2025 年 11 月 30 日, 在 PHP 生态内属于活跃度较高的组件。
它主要适用于以下技术方向: 「cache」 「caching」 「proxy」 「decorator」 「psr-6」 等业务场景。在实际项目中,围绕这些方向常见需要落地的问题包括:接口对接、性能调优、并发安全、与既有框架(Laravel / ThinkPHP / Yii / Webman 等)的兼容适配,以及生产环境的日志埋点与稳定性保障。
我们在过去多个企业项目中使用过 coroq/with-cache 或与其功能相近的方案,如果你在选型或落地过程中遇到问题,例如 版本兼容、二次改造、私有化封装、与内部系统对接、生产 BUG 排查,欢迎联系我们协助评估。
基于 coroq/with-cache 在你已有业务上做功能扩展、字段裁剪、UI 适配、与内部账号 / 权限 / 日志系统的深度对接。
线上偶发问题、内存泄漏、慢查询、并发异常等排查修复;针对高流量场景做缓存、队列、索引层面的调优。
承接完整的项目从需求 → 设计 → 开发 → 上线 → 长期运维;也可按月提供技术保姆服务。
与 coroq/with-cache 相关的其它包
同方向 / 同关键字的高下载量 PHP Composer 包推荐,方便对比选型:
Lazy loading for middleware and request handlers
repository php library
Query caching for Laravel 5
Laravel 5 - Repositories to the database layer
Simple PHP caching system that uses a tmp folder in a Linux environment.
Provides support for PSR-6 compatible cache for Yii1 application
统计信息
- 总下载量: 0
- 月度下载量: 0
- 日度下载量: 0
- 收藏数: 0
- 点击次数: 25
- 依赖项目数: 0
- 推荐数: 0
其他信息
- 授权协议: MIT
- 更新时间: 2025-11-30