Given that in the previous section I finished developing an example class that could store basic information on some users, it’s time to demonstrate how this class can be used within the schema imposed for the eager loading pattern.
So, take a close look at the following script. Despite its simplicity, it shows in a nutshell the logic that stands behind using eager loading:
/* rest of script code
// create instance of 'User' class
$user = new User();
// display user data
What’s the big deal with this script? Not too much, really. But in this particular case, there’s a couple of things that are worth noting. The first one is the use of the “require_once” PHP function at the beginning, which naturally includes the previous “User” class, provided that its definition has been saved to a file called “user.php.”
Then, the script performs other tasks; in the end it creates an instance of the class in question and displays the values of its properties on the screen. This simple sequence of steps shows very clearly the rationale behind eager loading; since the class is included “eagerly,” before the script really needs to spawns an object from it.
What’s more, if the rest of the script is modified, the whole class still would be included, regardless of whether or not it is used at a later time. This particular example recreates a situation where eager loading is implemented inefficiently, but as I mentioned in the introduction, there are cases where this pattern can be extremely useful, particularly when it’s necessary to “prefetch” database rows.
But for the moment, I’m only scratching the surface when it comes to exploring the facets of the eager loading pattern. It’s a huge topic that I plan to cover in upcoming tutorials of this series. In the meantime, feel free to edit all the code samples shown in this article, so you can acquire a more solid background in using this design pattern with PHP 5.
In this introductory installment of the series, I provided you with a basic example of how to implement the eager loading design pattern in a few simple steps when working with PHP 5. In this case, the pattern was applied thanks to the eager inclusion of a basic class within a script, regardless of whether or not it was directly requested by the script, which in this particular case introduced an unnecessary overhead.
Does this mean that eager loading is a bad thing? Not at all; this depends strongly on the context where the pattern is applied. But if the example shown previously didn’t dissipate your doubts on the implementation of this pattern, in the next article I’m going to create for you another program that will use a stricter object-oriented approach for eager loading with the earlier “User” class.
Don’t miss the following part!
blog comments powered by Disqus