DEV Community

Adamo Crespi for Serendipity HQ

Posted on • Originally published at io.serendipityhq.com on

How to lazy load objects in PHP

Lazy loading is a mechanism that make the script able to load data only when they are required to.

So, if we have to load a big graph of data, we don’t load it entirely at the start, but only when it is required for use.

This mechanism is very useful as it maintain the application performances high (if used with cause cognition!).

Start implementing this mechanism in our apps could be really complex, especially if we have no confidence with some patterns that are behind it, as the Proxy or Observer patterns are.

The really important thing to remember in approaching those kind of tasks is the Liskov Substitution Principle: in simple words, obj A and obj AProxy have to be used in the same context without breaking the application as the one can be substituted with the other.

There are 3 main kind of objects we can use to implement lazy loading:

  • Virtual objects : An object whose properties are all set to null and where each access to the properties is tracked and, once an access is intercepted, the lazy loading is triggered to get the current real value of the property;
  • Value Holder : holds an instance of the original proxied object and loads the real object (hydrated with real values) only when needed (this can be something different from a Value Object);
  • Ghost objects : An object whose properties are the same of the proxied object, but null. Accessing any method causes loading of the properties (this is the mechanism used by Doctrine lazy loading implementation).

There are some rules to follow implementing the Proxy Object:

  1. The Proxy class MUST extend the proxied class
  2. Each of the proxied methods must be rewritten
  3. Proxies should be serializable
  4. Proxies should handle public properties Ocramius about Proxy OOP Pattern in PHP

An example of a lazy loadable object generated by Doctrine:

Here some useful links about lazy loading in PHP.

Remember to “Make. Ideas. Happen.”.

I wish you flocking users, see you soon!

L'articolo How to lazy load objects in PHP proviene da ÐΞV Experiences by Serendipity HQ.

Top comments (0)