StructuralPHPverifiedVerified

Proxy Pattern in PHP

Provides a surrogate or placeholder for another object to control access, add lazy initialization, caching, logging, or access control.

How to Implement the Proxy Pattern in PHP

1Step 1: Define the subject interface

interface Image
{
    public function display(): string;
}

2Step 2: Implement the real (heavy) subject

class HighResImage implements Image
{
    private string $data;

    public function __construct(private readonly string $filename)
    {
        $this->data = "Loaded: {$filename}"; // Simulates expensive loading
        echo "HighResImage loaded: {$filename}\n";
    }

    public function display(): string
    {
        return $this->data;
    }
}

3Step 3: Implement the lazy-loading proxy

class ImageProxy implements Image
{
    private ?HighResImage $realImage = null;

    public function __construct(
        private readonly string $filename,
    ) {}

    public function display(): string
    {
        // Lazy initialization — only load when needed
        if ($this->realImage === null) {
            $this->realImage = new HighResImage($this->filename);
        }
        return $this->realImage->display();
    }
}

// Usage — image is not loaded until display() is called
$image = new ImageProxy('photo.jpg');
echo "Proxy created, image not loaded yet\n";
echo $image->display(); // Now the image is loaded

Proxy Pattern Architecture

hourglass_empty

Rendering diagram...

lightbulb

Proxy Pattern in the Real World

A corporate receptionist acts as a proxy for the CEO. When someone wants to meet the CEO, the receptionist checks credentials, schedules the meeting, and logs the visit before granting access. The visitor interacts with the receptionist using the same protocol they would use with the CEO—the receptionist simply adds control and record-keeping around that access.