Virtual Proxies revisited
Posted by John Kleijn • Thursday, March 25. 2010 • Category: PHPOf all the well known design patterns related to ORM, the Proxy pattern (or more specifically, Virtual Proxy) is perhaps the most under-appreciated (with Unit of Work Controller and Value List Handler coming in second). This may be because it's not strictly a data source pattern, and you won't find in PoEAA chapter or Core J2EE Patterns. It is actually in the GoF, which doesn't contain any data source patterns. For me personally, Virtual Proxy will always be directly associated with data loading, as that is what I first used it for in 2006, although since then I have used for other occasions where object initialization was abnormally expensive. It is a pretty versatile pattern.
In a nutshell, a Virtual Proxy is a "lazy loading" pattern that defers initialization of an object until it needed. The proxy does not contain the actual resource, but "knows how to get it". It does this by extending a subjects class while delegating to an instance of that same class, the subject. Basically this is what a Decorator does. But instead of overriding methods to add behaviour to a decorated object, it overrides them to trigger initialization of the subject (loading from the database in the case of an ORM), before delegating to the subject. Like with a decorator you'll have to override every method so that it is delegated to the subject. This makes manually writing proxies a pain.
»