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:
- The Proxy class MUST extend the proxied class
- Each of the proxied methods must be rewritten
- Proxies should be serializable
- 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.
- A very complete view on objects types that can be used to implement the lazy loading functionalities (by Marco “Ocramius” Pivetta);
- Another slide deck about the objects types that can be used to implement the lazy loading functionalities (ever by Marco “Ocramius” Pivetta);
- A question on StackOverflow about How does the Doctrine Repository mechanism of lazy loading entities work;
- How does it was implemented in Doctrine 2 (by Giorgio Sironi): Before the implementation and After the implementation;
- A further explanation of the Doctrine Proxy implementation (by Marco “Ocramius” Pivetta);
- How to implement the Proxy Pattern: Example 1 and Example 2 (lazy loading of images properties), Example 3 (retrieving lazily a list of books);
- Something about the Observer pattern;
- The Proxy Manager I’m using (compatible with both Zend Framework 2 and Symfony Framework 2);
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)