> For the complete documentation index, see [llms.txt](https://al-mamun.gitbook.io/al-mamun/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://al-mamun.gitbook.io/al-mamun/design-patterns/proxy-pattern.md).

# 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

```
Client
   ↓
Proxy
   ↓
Real Service
```

***

## 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

```
interface Image
{
    public function display();
}
```

***

## Step 2: Real Object

Heavy object.

```
class RealImage implements Image
{
    protected string $filename;

    public function __construct(string $filename)
    {
        $this->filename = $filename;

        $this->loadFromDisk();
    }

    protected function loadFromDisk()
    {
        echo "Loading {$this->filename} from disk...\n";
    }

    public function display()
    {
        echo "Displaying {$this->filename}\n";
    }
}
```

***

## Step 3: Proxy Class

```
class ProxyImage implements Image
{
    protected ?RealImage $realImage = null;

    protected string $filename;

    public function __construct(string $filename)
    {
        $this->filename = $filename;
    }

    public function display()
    {
        if ($this->realImage === null) {
            $this->realImage = new RealImage($this->filename);
        }

        $this->realImage->display();
    }
}
```

***

## Step 4: Usage

```
$image = new ProxyImage('large-photo.jpg');

echo "Image will load only when needed\n";

$image->display();

$image->display();
```

***

## Output

```
Image will load only when needed

Loading large-photo.jpg from disk...
Displaying large-photo.jpg
Displaying large-photo.jpg
```

***

## What Happened?

### First Call

```
display()
```

Proxy creates the real object.

***

### Second Call

Object already exists.

No reload needed ✅

***

## Why Use Proxy?

Without proxy:

```
$image = new RealImage('large-photo.jpg');
```

Large file loads immediately ❌

Even if never used.

***

## With Proxy

```
$image = new ProxyImage('large-photo.jpg');
```

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

```
class AdminProxy
{
    public function access($role)
    {
        if ($role !== 'admin') {
            return "Access Denied";
        }

        return "Welcome Admin";
    }
}
```

***

## Real Laravel Examples

### 1. Lazy Loading in Eloquent

```
$user->posts
```

Laravel loads relation only when needed.

Proxy-like behavior.

***

### 2. Cache Facade

```
Cache::remember()
```

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.
