As you may know, design patterns are proven, well-trusted solutions that tackle a specific problem that occurs frequently in software development. As with many other principles and paradigms in this area, some patterns are more popular and easier to learn than others, and when applied properly, can considerably improve the efficiency and performance of an application. This five-part article series will discuss two of these.
In the case of PHP 5, which is better suited for developing web-based programs, there are two complementary design patterns that can be of great help in building faster and more reliable applications. Of course, as this article’s title suggests, I’m talking about the lazy and eager loading patterns. Despite their rather funny names, they are pretty easy to implement in PHP 5-controlled environments.
But before I start coding some functional examples in the next few lines, it would be useful to explain briefly what these patterns actually are, so you'll understand their underlying logic. First, the expression “lazy loading” refers to the ability of a program to load a specific resource only at the time it’s required, and not before.
In this case, a resource can be anything that fits in into a program’s context, ranging from one or multiple classes, functions, database result sets, one or more objects, and so forth (feel free to add your own to the list). Naturally, lazy loading is a powerful pattern that very often is used in PHP 5 to speed up the performance of database-driven applications.
For instance, it’s possible to “delay” or defer the instantiation of a certain class until a program really requests this process, thus preventing the overhead of storing an object in memory that will remain unused most of the time. In this example, this procedure would be called “lazy initialization.”
On the other hand, eager loading is the opposite of lazy loading. It simply refers to the process of loading or prefetching a resource with anticipation, regardless of whether or not it will be required by a program. At first glance, it seems to be a rather inefficient approach, but this is merely a misconception, trust me. Certainly, one common use of eager loading is when processing database result sets retrieved from two or more related tables. In a situation like this, it would be possible to prefetch all of the child records associated with a row in a parent table, in this way avoiding the need to perform additional queries.
At this time, are you capable of spotting the differences between using lazy and eager loading? I hope so. But to clear up your doubts, in this group of articles I’m going to show you how to apply these powerful design patterns in some concrete situations using PHP 5. So start reading!