PHP Object Lazy-Loading is More Than What You Think

JoliCode - JoliCodeBlog - 26/03
We recently attended a talk about lazy-loading by Nicolas Grekas and it inspired me this blogpost! We can find lazy-loading in all modern PHP applications, in ORMs, for example. But is there more usage of lazy-loading? What is lazy-loading? In short: lazy-loading consists of delaying

We recently attended a talk about lazy-loading by Nicolas Grekas and it inspired me this blogpost!

We can find lazy-loading in all modern PHP applications, in ORMs, for example. But is there more usage of lazy-loading?

Section intitulée what-is-lazy-loadingWhat is lazy-loading?

In short: lazy-loading consists of delaying load or initialization of resources or objects until they’re actually needed. It’s something you will never see directly, the whole objective of lazy-loading is to be invisible so you can use your applications the way you always do.

And behind this invisible thing, we will give you something that will act as the object you want but will only load its content when required.

We can see two main pros about using lazy-loading:

  • It will save memory and CPU until we load the data
  • It may never be called since you sometimes load nested objects that you don’t need…

What is lazy-loading? Martin Fowler, in his book “Patterns of Enterprise Application Architecture”, explains this pattern very well. There are 4 types of lazy-loading patterns. Each of them have pros & cons:

  • Lazy initialization, your object contains a null property and whenever you need that property, it will initialize it. In that case, your object needs to be aware that it is lazy-loaded;
  • Value holders, it’s an object that is responsible for initializing another object whenever you need it. It will require you to write a different class but the base class will stays the same;
  • Virtual proxy is an object that is using the same interface (methods) that is used in the base object and whenever you use one of those methods, it will instantiate the base object and delegate to it;
  • Ghost objects are objects that are to be loaded in a partial state. It may initially only contain the object’s identifier, but it loads its own data the first time one of its properties or methods are accessed.

In PHP we have some libraries that implement this pattern such as ProxyManager, Proxy Manager LTS or even symfony/var-exporter. I do personally recommend using the latter when possible.

One of the biggest drawbacks of Ghost objects is that you need to create a class that extends the proxified class. It can block you if you want to proxify a class that is final...
[Courte citation de 8% de l'article original]

Loading...