Caching behavior
Cache the results of slow methods with one attribute. A #[Cacheable] behavior with PSR-16 storage that works on final classes, readonly classes and static methods.
Your manager forwards a complaint: the checkout page takes three seconds. The profiler points at one method that asks a remote service for an exchange rate on every call, although the rate changes a few times a day. The answer is obvious: cache it. Where the caching code goes is the interesting part.
This page walks from the quick fix to a caching behavior: you mark a method with #[Cacheable], and the framework runs the cache lookup as middleware around it. The words behavior class, behavior and matching rule are explained in the terms table.
The problem
Section titled “The problem”The slow service:
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 }}The quick fix puts the cache into the method:
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; }}It works, and it starts to spread:
- The class has two jobs. It fetches rates and manages a cache. Every test of
ExchangeRatesnow needs a cache, and the cache dependency travels into every constructor call. - The same lines are copied into every slow method. Each copy builds its own key, picks its own lifetime and handles misses its own way. Sooner or later one copy forgets an argument in the key and returns the wrong data.
- There is no single place to change it. Turning the cache off for a test run, renaming keys or switching the storage means editing every copy.
Why decorators and proxies fall short
Section titled “Why decorators and proxies fall short”Object-oriented design has two classic answers, and modern PHP code blocks both:
- A caching subclass overrides the slow methods and calls
parent::rate()on a miss. It can’t extend afinalclass, and many modern services arefinal readonly. - A decorator wraps the service and implements the same interface. It needs an interface for every service and a forwarding method for every method, cached or not. A generic
__call()proxy saves the typing but is no longer anExchangeRates, so every type hint rejects it. - Neither can cache a static method. Callers name the class directly, so there is nothing to wrap.
The caching behavior
Section titled “The caching behavior”The caching logic goes into one behavior class, and the methods that need it are marked with an attribute. Four small files.
1. The attribute
Section titled “1. The attribute”namespace App\Attribute;
use Attribute;
#[Attribute(Attribute::TARGET_METHOD)]final readonly class Cacheable{ public function __construct(public int $ttl = 300) {}}An ordinary PHP attribute. It carries the setting that differs between methods, the lifetime in seconds, and has no dependency on the framework.
2. Mark the method
Section titled “2. Mark the method”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); }}The method is back to one line, and the class has one dependency again.
3. The behavior class
Section titled “3. The 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] runs the behavior in place of the method. The matching rule @execution(App\Attribute\Cacheable) selects every method that carries the attribute. Inside:
- The key names the class, the method and the arguments, so
rate('EUR', 'USD')andrate('USD', 'EUR')get separate entries. It is hashed because PSR-16 reserves the characters{}()/\@:and only guarantees keys of up to 64 characters. $missis a fresh object that no cache can return, so methods that returnnullorfalseare cached too.proceed()runs the original method, only on a miss. The lifetime comes from the attribute on that method.getScope()returns the class name for instance calls and for static calls alike.getThis()would benullfor a static call.
4. Register the behavior class
Section titled “4. Register the 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)), ); }}The cache comes from your application container once it is attached with setDelegate() (see Dependencies). With the Symfony, Laravel or Yii3 bridge you skip this step: the behavior class is an autowired service like any other (Integrations). Any PSR-16 implementation works, for example symfony/cache with Psr16Cache.
What you get
Section titled “What you get”$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 and readonly classes work. The class keeps its name and its
final readonlydeclaration. Type hints,instanceofandnew ExchangeRates(...)are unchanged, because no wrapper object exists. -
Static methods work too, which no decorator can do:
final class Countries{#[Cacheable(ttl: 86400)]public static function all(): array{// reads a large file}} -
One place to change. The key scheme, the storage and the rules live in
CachingAspect. Marking or unmarking a method is a one-line change in a reviewable diff. -
You can check it.
vendor/bin/aspect debug:advisor public/index.php --advisor=...lists every method the rule selects (see debug:advisor), and a breakpoint insidecache()stops on each cached call. -
The cost is small. Intercepting a call costs under 1 µs (measured costs), against the seconds of a remote call.
Details to decide
Section titled “Details to decide”- Arguments must be serializable.
serialize()throws for closures and for some objects. For entities, pass their identifiers to cached methods, or build the key from the parts you need. - The object’s state is not in the key. Two
ExchangeRatesinstances with different sources share entries. If the result depends on the instance, add a value that identifies it to the key. - Invalidation. Phil Karlton’s line still holds: there are only two hard things in computer science, cache invalidation and naming things. A lifetime is the simplest policy. When data must disappear the moment it changes, use a cache that supports tags (for example Symfony’s
TagAwareCacheInterface) and a second behavior on the methods that write the data. - Narrow the rule if you need to. Combine the attribute with other rules, for example
@execution(App\Attribute\Cacheable) && within(App\Service\**). The syntax is in Matching rules.
© 2026 Alexander Lisachenko
