HomePHP Page 4 - Deferring Class Property Creation with Lazy Loading
Building a final script - PHP
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 I promised in the section that you just read, below I coded a sample script that shows how to add on request some properties to an instance of the "User" class defined previously. Here's the script:
// create instance of 'User' class
$user = new User();
// create some properties
$user->fname = 'Alejandro';
$user->lname = 'Gervasio';
$user->email = 'email@example.com';
// display user data
As you can see from the above example, once an instance of the "User" class has been properly spawned, it's really easy to add to it some properties on the fly, which shows that applying the lazy loading pattern to the properties in question is indeed very simple.
And finally, with this last example I'm finishing this series of articles about implementing eager and lazy loading in PHP-driven environments. Of course, I'm only scratching the surface when it comes to using these patterns in real-world cases, but hopefully the set of examples that you learned in these tutorials will give you a good idea of how to utilize them in some other useful ways.
It's hard to believe, but we've come to the end of this series. Hopefully this journey has been educational, since in it you learned how to implement the lazy and eager loading patterns in different cases using PHP 5.
As you saw through the code samples shown here, when used in a clever way these patterns can be really powerful for boosting the performance of web applications, particularly of those that work with databases and rely on an object-oriented approach to perform different tasks.