HomePHP Deferring Class Property Creation with Lazy Loading
Deferring Class Property Creation with Lazy Loading
Welcome to the conclusion of a five part series that shows you how to implement lazy and eager loading in PHP 5. These two design patterns allow you to handle the resources for an application in very different ways. Through numerous code examples, I've demonstrated when it is appropriate to use each method.
As you may know as a PHP programmer, one of the most important facets that must be tackled during the development of a web application is properly establishing the way that its resources will be managed. While there are many factors involved in this process that will affect, both directly and indirectly, the end performance of a certain program, it's possible to use well-trusted approaches to define how "early" a specific resource will be loaded by the program in question.
In software programming, there are two design patterns that permit you to achieve this definition procedure with relative ease, popularly known as lazy and eager loading. As you may have guessed, in the first case loading a determined resource will be delayed or deferred until an application (or a part of it) actually requests it, while in the last case the resource will be loaded as soon as possible, regardless of whether or not it's required by the application.
In this particular context, the term "resource" references anything suitable to use within a PHP-driven program, ranging from classes to objects, configuration files, database result sets and so forth. How much success you can achieve when applying the aforementioned patterns will depend strongly on the type of resource you're handling.
However, if you've been a loyal follower of this article series and have already read all of the tutorials that precede this one, then it's probable that at this point you're familiar with using eager and easy loading in PHP 5. In those articles I explained how to apply these patterns when including a class within a script, as well as when declaring and assigning values to its properties.
This last scenario was recreated in the last article, where I showed how a class that stored user-related data eagerly assigned default values to its declared properties, showing that eager loading can be used in many different cases.
Nevertheless, if it was possible to eagerly handle properties of a class, then in theory it would also be feasible to invert the process and manipulate those properties in a lazy fashion, right? Well, that's true, and in this final chapter of this series I'm going to show you through some code samples how to accomplish this with minor hassles.