All posts
Published in design patterns

Proxy Design Pattern in PHP

Profile image of Atakan Demircioğlu
By Atakan Demircioğlu
Fullstack Developer

In this post, I will share my notes about Proxy Design Pattern in PHP.

Proxy Design Pattern in PHP image 1

The Proxy Pattern is a structural design pattern that acts as a substitute or placeholder for another object.

It controls access to the real object, allowing you to perform additional actions before or after accessing the original object.

This pattern is useful for scenarios where you want to add functionality such as logging, caching, or access control without modifying the original object.

What is the difference between Decorator and Proxy Pattern?

The Decorator Pattern and the Proxy Pattern are both structural design patterns that involve wrapping objects with other objects. However, they serve different intents.

Proxy Pattern is primarily used to control access to an object, acting as a surrogate or placeholder for another object. It does not alter the interface of the original object but instead provides a way to intercept and manage access to it, allowing for additional functionalities such as lazy initialization, access control, logging, etc.

A decorator adds one or more responsibilities to an object, whereas a proxy controls access to an object.

A Decorator requires an instance of the interface it is wrapping, while a Proxy does not require such an instance

Decorators are additive but Proxy is restrictive.

Decorators are for general purposes. It can add some functionality regardless of the instance that is wrapped.

Example Proxy Pattern in PHP

As I said there are different types and usages of Proxy pattern. In this example, I am using the Proxy Pattern to avoid loading again a heavy thing.

 

 

In the second example, I am dumping any log before calling the real object.