🐘 PHP Advanced

What is the Proxy pattern in PHP?

Answer

The Proxy pattern provides a surrogate or placeholder object that controls access to another object. The proxy implements the same interface as the real subject and delegates work to it, while adding its own behavior. Types: Virtual Proxy (lazy initialization — creates the expensive object only when first needed), Protection Proxy (access control — checks permissions before forwarding), Remote Proxy (represents an object in a different address space), and Caching Proxy (caches results of expensive operations). PHP example: a LazyUserRepository proxy that only loads the database connection the first time a query is made. Laravel's Eloquent lazy loading relationships is a form of virtual proxy — related models are loaded only when accessed. Doctrine ORM uses proxy classes extensively for lazy-loading entities.