Sooner or later every repository gets the same request: can we cache this? The quickest answer is to drop Cache::remember() straight into the repository methods.
You can. I did it for years. The problem shows up a few months later, when the same class also logs slow queries, emits metrics, and has a feature flag that skips the cache in staging. At that point the actual query is three lines buried in twenty lines of plumbing.
The Decorator pattern solves this in a boring, predictable way, and boring is exactly what you want in infrastructure code. A decorator implements the same interface as the object it wraps, holds a reference to it, and adds behaviour before or after delegating. The caller never knows the difference.
The starting point
Here is the repository we will work with, a plain order repository for a small shop. The interface is deliberately small:
namespace App\Repositories;
use App\Models\Order;
use Illuminate\Support\Collection;
interface OrderRepository
{
public function findById(int $id): ?Order;
public function recentForCustomer(int $customerId): Collection;
public function save(Order $order): void;
}PHPAnd the Eloquent implementation, which only knows how to talk to the database:
final class EloquentOrderRepository implements OrderRepository
{
public function findById(int $id): ?Order
{
return Order::query()->with('items')->find($id);
}
public function recentForCustomer(int $customerId): Collection
{
return Order::query()
->where('customer_id', $customerId)
->latest()
->limit(10)
->get();
}
public function save(Order $order): void
{
$order->save();
}
}PHPWe are not going to touch this class again. That is the whole point of the exercise.
Decorator #1: caching
The caching decorator implements OrderRepository, receives another OrderRepository in its constructor, and wraps the reads:
namespace App\Repositories;
use App\Models\Order;
use Illuminate\Contracts\Cache\Repository as Cache;
use Illuminate\Support\Collection;
final class CachingOrderRepository implements OrderRepository
{
private const TTL = 600; // seconds
public function __construct(
private readonly OrderRepository $inner,
private readonly Cache $cache,
) {}
public function findById(int $id): ?Order
{
return $this->cache->remember(
"orders.{$id}",
self::TTL,
fn () => $this->inner->findById($id),
);
}
public function recentForCustomer(int $customerId): Collection
{
return $this->cache->remember(
"orders.customer.{$customerId}.recent",
self::TTL,
fn () => $this->inner->recentForCustomer($customerId),
);
}
public function save(Order $order): void
{
$this->inner->save($order);
$this->cache->forget("orders.{$order->id}");
$this->cache->forget("orders.customer.{$order->customer_id}.recent");
}
}PHPA few things worth pointing out.
The type hint is OrderRepository, not EloquentOrderRepository. The decorator has no idea what it wraps. It could be Eloquent, an HTTP client for a legacy API, or another decorator.
I use explicit keys instead of cache tags. Tags only work with drivers like Redis or Memcached, and I have been burned by a project that switched to the database driver and silently lost invalidation. Explicit forget() calls are dull but they work everywhere.
One gotcha that cost me an afternoon once: remember() treats a cached null as a miss. So findById() for an order that does not exist hits the database every time. Usually that is fine. If it is not, cache a sentinel value instead.
Decorator #2: logging slow calls
Same shape, different concern. This one measures each call and logs a warning when it is slow:
namespace App\Repositories;
use App\Models\Order;
use Illuminate\Support\Collection;
use Psr\Log\LoggerInterface;
final class LoggingOrderRepository implements OrderRepository
{
public function __construct(
private readonly OrderRepository $inner,
private readonly LoggerInterface $logger,
private readonly int $slowThresholdMs = 200,
) {}
public function findById(int $id): ?Order
{
return $this->measure(__FUNCTION__, fn () => $this->inner->findById($id));
}
public function recentForCustomer(int $customerId): Collection
{
return $this->measure(__FUNCTION__, fn () => $this->inner->recentForCustomer($customerId));
}
public function save(Order $order): void
{
$this->measure(__FUNCTION__, fn () => $this->inner->save($order));
}
private function measure(string $method, callable $call): mixed
{
$start = hrtime(true);
try {
return $call();
} finally {
$ms = (hrtime(true) - $start) / 1_000_000;
if ($ms > $this->slowThresholdMs) {
$this->logger->warning('Slow OrderRepository call', [
'method' => $method,
'ms' => round($ms, 1),
]);
}
}
}
}PHPThe finally block matters. If the inner call throws, we still log the duration, and the exception keeps bubbling up untouched. A decorator should never swallow errors it was not built to handle.
Wiring it up with extend()
This is the part most Laravel tutorials skip. You could build the whole chain by hand in a single closure, and for a small app that is perfectly fine. But the container has a method made for exactly this: extend(). It lets you wrap an existing binding without redefining it.
namespace App\Providers;
use App\Repositories\CachingOrderRepository;
use App\Repositories\EloquentOrderRepository;
use App\Repositories\LoggingOrderRepository;
use App\Repositories\OrderRepository;
use Illuminate\Contracts\Cache\Repository as Cache;
use Illuminate\Contracts\Foundation\Application;
use Illuminate\Support\ServiceProvider;
use Psr\Log\LoggerInterface;
class RepositoryServiceProvider extends ServiceProvider
{
public function register(): void
{
$this->app->singleton(OrderRepository::class, EloquentOrderRepository::class);
$this->app->extend(OrderRepository::class, function (OrderRepository $repo, Application $app) {
return new CachingOrderRepository($repo, $app->make(Cache::class));
});
$this->app->extend(OrderRepository::class, function (OrderRepository $repo, Application $app) {
return new LoggingOrderRepository($repo, $app->make(LoggerInterface::class));
});
}
}PHPExtenders run in the order you register them, and each one receives the result of the previous one. So the chain above looks like this:
LoggingOrderRepository
-> CachingOrderRepository
-> EloquentOrderRepositoryPHPYour controllers and services keep asking for OrderRepository and get the whole stack. Nothing else in the codebase changes.
Order is a decision, not a detail
With logging on the outside, every call is measured, including cache hits. That tells you how fast the repository feels to the caller. Swap the two extend() calls and logging sits between the cache and the database, so it only sees real queries. Neither is wrong. Pick the one that answers the question you actually have. In my case it was “which queries are slow”, so in production I ended up with logging on the inside.
Where extend() really earns its keep is across providers. The base binding can live in a domain module, and a separate OrderCachingServiceProvider can add caching without ever opening that module. Just remember that the providers’ registration order now decides the order of the decorators. I also like that I can drop a decorator in tests or locally by wrapping one extend() call in an if.
Why not just extend the class?
The tempting alternative is class CachingEloquentOrderRepository extends EloquentOrderRepository. It works until you want logging too. Then you need LoggingCachingEloquentOrderRepository, and a separate one for the version without cache. Inheritance makes you pick the combinations up front. Composition lets you stack them at runtime.
This is the Open/Closed principle without the textbook tone. EloquentOrderRepository is closed: we did not edit it. The system is open: we added two behaviours by adding two classes. Each class also has exactly one reason to change, which keeps Single Responsibility happy, and every consumer depends on the interface, which is plain Dependency Inversion.
Testing a decorator in isolation
Because each decorator only cares about the interface, you can test it without a database. Mock the inner repository, give it an in-memory cache store, and check that the second call never reaches the inner object:
use App\Models\Order;
use App\Repositories\CachingOrderRepository;
use App\Repositories\OrderRepository;
use Illuminate\Support\Facades\Cache;
use Tests\TestCase;
class CachingOrderRepositoryTest extends TestCase
{
public function test_second_read_is_served_from_cache(): void
{
$order = Order::factory()->make(['id' => 42]);
$inner = $this->mock(OrderRepository::class);
$inner->shouldReceive('findById')->once()->with(42)->andReturn($order);
$repo = new CachingOrderRepository($inner, Cache::store('array'));
$this->assertSame(42, $repo->findById(42)->id);
$this->assertSame(42, $repo->findById(42)->id);
}
}PHPThe once() expectation does the real work. If caching breaks, Mockery fails the test because findById() was called twice. The EloquentOrderRepository keeps its own integration tests against a real database, and the two concerns never mix.
When I would not reach for it
Decorators are cheap, but they are not free.
- Fat interfaces. If
OrderRepositoryhad fifteen methods, every decorator would need fifteen methods, most of them one-line pass-throughs. That is not a decorator problem. It is the interface telling you it should be split. - Behaviour that needs internals. A decorator only sees inputs and outputs. If the new logic needs access to the query builder or private state, it belongs in the implementation, not around it.
- Too many layers. Three decorators are readable. Six turn every stack trace into an archaeology dig. If you find yourself stacking that many, a pipeline or middleware approach is probably a better fit.
- Caching rich models blindly. A cached
Ordercomes back with whatever relations it had when it was stored. Keep the TTL short, or cache plain data instead of full models when freshness matters.
Wrapping up
The Decorator pattern does not look impressive in a diagram. In a real codebase it means your Eloquent repository stays a dozen lines of queries, caching lives in one class you can delete in a minute, and logging can be switched on for a single repository without touching anything else.
If you already have repositories in your project, try it on the one that gets the most traffic. Add the caching decorator, wire it with extend(), and see how little of the existing code you had to change. That small diff is usually the most convincing argument for the pattern.

