For the complete documentation index, see llms.txt. This page is also available as Markdown.

Proxy Pattern

The Proxy Pattern is a structural design pattern that provides a placeholder or representative object to control access to another object.

Instead of accessing the real object directly, the client communicates through a proxy.

The proxy can:

  • Control access

  • Add security

  • Add caching

  • Delay object creation

  • Log requests


Real Life Example

Think about an ATM Card 💳

You do not directly access the bank server.

Flow:

Client

Proxy

Real Service

The ATM card:

  • Verifies PIN

  • Checks permissions

  • Controls access

This is Proxy Pattern.


Structure


Laravel / PHP Example

Scenario

We are building an image loader.

Large images are expensive to load.

We use a proxy to:

  • Delay loading

  • Load only when needed

This is called Virtual Proxy.


Step 1: Subject Interface


Step 2: Real Object

Heavy object.


Step 3: Proxy Class


Step 4: Usage


Output


What Happened?

First Call

Proxy creates the real object.


Second Call

Object already exists.

No reload needed ✅


Why Use Proxy?

Without proxy:

Large file loads immediately ❌

Even if never used.


With Proxy

Loads only when required ✅


Types of Proxy Pattern

Type
Purpose

Virtual Proxy

Lazy loading

Protection Proxy

Access control

Remote Proxy

Remote service communication

Caching Proxy

Store previous results

Logging Proxy

Monitor requests


Protection Proxy Example


Real Laravel Examples

1. Lazy Loading in Eloquent

Laravel loads relation only when needed.

Proxy-like behavior.


2. Cache Facade

Acts like caching proxy.


3. Middleware

Middleware controls access before request reaches controller.

Proxy behavior.


Advantages

1. Lazy Loading

Load expensive objects only when needed.


2. Security Control

Can restrict unauthorized access.


3. Performance Optimization

Caching and delayed initialization improve performance.


4. Logging & Monitoring

Track access transparently.


Proxy vs Decorator

Proxy
Decorator

Controls access

Adds behavior

May delay execution

Enhances functionality

Focus on control

Focus on extension


Proxy vs Facade

Proxy
Facade

Controls one object

Simplifies many objects

Same interface as real object

Different simplified interface

Access management

Complexity reduction


When to Use Proxy Pattern

Use Proxy Pattern when:

✅ Object creation is expensive ✅ Lazy loading is needed ✅ Access control is required ✅ Logging/caching needed ✅ Remote object communication exists


Short Interview Definition

The Proxy Pattern provides a surrogate or placeholder object that controls access to another object.

Last updated