What It Is
The Proxy pattern puts a stand-in with the same interface in front of a real object. Callers talk to the proxy as if it were the real thing; the proxy decides when and how to involve the original.
Common jobs for a proxy: caching answers, checking access, delaying expensive creation, counting calls.
Example: A Caching Proxy
The real weather service is slow. The proxy answers repeated questions from its cache and only calls the service for new ones — behind the very same interface.
The stand-in that remembers
The first Paris question reaches the remote service; the second is answered from the cache — the "calling the remote service" line prints only once. One isset check on the cache array decides which path a question takes.
Output: PHP script
<?php
interface Weather {
public function forecast(string $city): string;
}
// The real service is slow and expensive.
class WeatherService implements Weather {
public function forecast(string $city): string {
echo " (calling the remote service...)\n";
return "sunny in " . $city;
}
}
// The proxy stands in front and caches answers.
class CachedWeather implements Weather {
/** @var array<string, string> */
private array $cache = [];
public function __construct(private WeatherService $service) {}
public function forecast(string $city): string {
if (isset($this->cache[$city])) {
return $this->cache[$city] . " (from cache)";
}
$answer = $this->service->forecast($city);
$this->cache[$city] = $answer;
return $answer;
}
}
$w = new CachedWeather(new WeatherService());
echo $w->forecast("Paris"), "\n";
echo $w->forecast("Paris"), "\n";
When to Use It
Use it to add caching, access control, laziness or metering in front of something you cannot or should not change — especially remote or expensive resources.
Skip it when you own the object and the behavior belongs inside it. A proxy is for controlling access; a decorator is for adding behavior in layers — pick the intent that matches.
Pros and Cons
Pros: callers need no changes at all; expensive work is skipped or controlled in one place.
Cons: hidden behavior — a caller may get a cached answer without knowing; stale caches and surprise denials are debugged behind an innocent-looking interface.