缓存行为
只需一个注解,就能缓存慢方法的结果。基于 PSR-16 存储的 #[Cacheable] behavior,可用于 final 类、readonly 类和静态方法。
本页译自英文,以英文页面为准。 阅读原文
经理转来一条投诉:结账页面要三秒才能打开。profiler 指向一个方法:它每次调用都要向远程服务查询汇率,而汇率一天只变几次。答案显而易见:缓存它。真正值得讨论的是,缓存代码该放在哪里。
本页从临时修补一路讲到缓存 behavior(行为):你用 #[Cacheable] 标记一个方法,框架就会把缓存查询作为 middleware(中间件)在它周围运行。behavior class(行为类)、behavior 和 matching rule(匹配规则)这几个词的含义见 术语表。
这个慢服务:
final readonly class ExchangeRates{ public function __construct(private RateSource $source) {}
public function rate(string $from, string $to): float { return $this->source->fetch($from, $to); // a remote call, ~1 s }}临时修补的做法是把缓存写进方法里:
use Psr\SimpleCache\CacheInterface;
final readonly class ExchangeRates{ public function __construct( private RateSource $source, private CacheInterface $cache, ) {}
public function rate(string $from, string $to): float { $key = "rate.$from.$to"; $rate = $this->cache->get($key); if ($rate === null) { $rate = $this->source->fetch($from, $to); $this->cache->set($key, $rate, 600); }
return $rate; }}它能用,但很快就开始蔓延:
- 一个类干了两份活。 它既要获取汇率,又要管理缓存。现在
ExchangeRates的每个测试都需要一个缓存,缓存依赖也会跟着进入每一次构造函数调用。 - 同样的几行代码被复制到每个慢方法里。 每份副本各自拼键、各自选过期时间、各自处理未命中。迟早有一份副本会在键里漏掉某个参数,返回错误的数据。
- 没有统一修改的地方。 想在一次测试运行中关掉缓存、重命名键,或者更换存储,就得逐一修改每份副本。
为什么装饰器和代理力不从心
Section titled “为什么装饰器和代理力不从心”面向对象设计有两种经典方案,而现代 PHP 代码把两条路都堵上了:
- 带缓存的子类覆写慢方法,在未命中时调用
parent::rate()。它无法继承final类,而很多现代服务都是final readonly的。 - 装饰器包装服务并实现同一个接口。它要求每个服务都有接口,并为每个方法(无论是否需要缓存)写一个转发方法。通用的
__call()代理能省去这些代码,但它已经不再是ExchangeRates,所有类型声明都会拒绝它。 - 两者都无法缓存静态方法。 调用方直接写出类名,根本没有可以包装的东西。
缓存 behavior
Section titled “缓存 behavior”缓存逻辑放进一个 behavior class,需要它的方法用一个注解标记。一共四个小文件。
namespace App\Attribute;
use Attribute;
#[Attribute(Attribute::TARGET_METHOD)]final readonly class Cacheable{ public function __construct(public int $ttl = 300) {}}一个普通的 PHP 注解。它携带各方法之间不同的那个设置,即以秒为单位的过期时间,并且不依赖框架。
2. 标记方法
Section titled “2. 标记方法”use App\Attribute\Cacheable;
final readonly class ExchangeRates{ public function __construct(private RateSource $source) {}
#[Cacheable(ttl: 600)] public function rate(string $from, string $to): float { return $this->source->fetch($from, $to); }}方法又回到了一行,类也重新只有一个依赖。
3. Behavior class
Section titled “3. Behavior class”namespace App\Aspect;
use App\Attribute\Cacheable;use Go\Aop\Aspect;use Go\Aop\Intercept\MethodInvocation;use Go\Lang\Attribute\Around;use Psr\SimpleCache\CacheInterface;
final class CachingAspect implements Aspect{ public function __construct(private readonly CacheInterface $cache) {}
#[Around('@execution(App\Attribute\Cacheable)')] public function cache(MethodInvocation $invocation): mixed { $method = $invocation->getMethod(); $key = 'call.' . hash('xxh128', $invocation->getScope() . '::' . $method->name . serialize($invocation->getArguments()));
$miss = new \stdClass(); $value = $this->cache->get($key, $miss); if ($value !== $miss) { return $value; }
$ttl = $method->getAttributes(Cacheable::class)[0]->newInstance()->ttl; $value = $invocation->proceed(); $this->cache->set($key, $value, $ttl);
return $value; }}#[Around] 让 behavior 代替方法运行。Matching rule @execution(App\Attribute\Cacheable) 选中所有带这个注解的方法。在 behavior 内部:
- 键包含类名、方法名和参数,因此
rate('EUR', 'USD')和rate('USD', 'EUR')会得到各自独立的条目。之所以做哈希,是因为 PSR-16 保留了{}()/\@:这些字符,而且只保证最长 64 个字符的键可用。 $miss是一个新建的对象,任何缓存都不可能返回它,因此返回null或false的方法同样会被缓存。proceed()运行原始方法,只在未命中时调用。过期时间取自该方法上的注解。getScope()无论是实例调用还是静态调用,都返回类名。而对于静态调用,getThis()会是null。
4. 注册 behavior class
Section titled “4. 注册 behavior class”use App\Aspect\CachingAspect;use Go\Core\AspectContainer;use Go\Core\AspectKernel;use Psr\SimpleCache\CacheInterface;
final class AppKernel extends AspectKernel{ protected function configureAop(AspectContainer $container): void { $container->addLazyService( CachingAspect::class, static fn(AspectContainer $c) => new CachingAspect($c->getService(CacheInterface::class)), ); }}缓存来自你的应用容器,前提是已用 setDelegate() 把它挂接上(见 依赖)。如果使用 Symfony、Laravel 或 Yii3 的桥接包,可以跳过这一步:behavior class 和其他服务一样是自动装配的服务(集成)。任何 PSR-16 实现都可以,例如 symfony/cache 配合 Psr16Cache。
你得到了什么
Section titled “你得到了什么”$rates->rate('EUR', 'USD'); // calls the remote service, stores the result for 600 s$rates->rate('EUR', 'USD'); // returns the stored rate$rates->rate('USD', 'EUR'); // other arguments: calls the remote service-
final 类和 readonly 类照常可用。 类保留自己的类名和
final readonly声明。类型声明、instanceof和new ExchangeRates(...)都不受影响,因为根本不存在包装对象。 -
静态方法也可以,这是任何装饰器都做不到的:
final class Countries{#[Cacheable(ttl: 86400)]public static function all(): array{// reads a large file}} -
只有一处需要修改。 键的生成方式、存储和规则都在
CachingAspect里。给方法加上或去掉标记,只是一次可审查 diff 中的一行改动。 -
你可以验证它。
vendor/bin/aspect debug:advisor public/index.php --advisor=...会列出规则选中的每个方法(见 debug:advisor),在cache()中设置的断点会在每次被缓存的调用时停下。 -
开销很小。 拦截一次调用的开销不到 1 µs(实测开销),而一次远程调用要花上几秒。
需要你决定的细节
Section titled “需要你决定的细节”- 参数必须可序列化。
serialize()遇到闭包和某些对象时会抛出异常。对于实体,向被缓存的方法传入它们的标识符,或者只用你需要的部分来拼键。 - 对象的状态不在键里。 两个使用不同数据源的
ExchangeRates实例会共享缓存条目。如果结果取决于实例本身,就在键里加入一个能标识该实例的值。 - 缓存失效。 Phil Karlton 那句话至今仍然成立:计算机科学中只有两件难事,缓存失效和命名。设置过期时间是最简单的策略。如果数据一变就必须立即失效,请使用支持标签的缓存(例如 Symfony 的
TagAwareCacheInterface),并在写数据的方法上再加一个 behavior。 - 必要时收窄规则。 把注解与其他规则组合使用,例如
@execution(App\Attribute\Cacheable) && within(App\Service\**)。语法见 匹配规则。
© 2026 Alexander Lisachenko
