As I mentioned in the introduction, lazy and eager loading are complementary patterns that have their own pros and cons, logically depending on the context where they’re applied. However, in this first part of the series I’m going to focus my attention specifically on the latter technique, so you can quickly grasp its rationale and decide where and when to use it. Having clarified that point, it’s time to demonstrate a basic usage of eager loading. I’m going to build a simple class. It will do nothing special except for storing data on some fictional users in the form of properties. Please, pay attention to the initial definition of this class, which is as follows: // define 'User' class class User {
private $fname = 'Alejandro'; private $lname = 'Gervasio'; private $email = 'alejandro@mydomain.com';
public function __construct($fname = '', $lname = '', $email = '') { if (is_string($fname) and !empty($fname)) { $this->fname = $fname; } if (is_string($lname) and !empty($lname)) { $this->lname = $lname; } if (is_string($email) and !empty($email)) { $this->email = $email; } } } Certainly, it's very easy to understand the way that the brand new “User” class functions. As I explained previously, it actually does nothing but save basic data on a particular user to their declared properties. Period. For this example, the assignment of new values to those properties is performed exclusively through the class’s constructor, but logically it’s possible to create some setter methods that do the same thing. So far, so good, right? At this stage, the “User” class in its current state is admittedly pretty useless, for the reason given earlier. If the class is only capable of storing user-related data, then it would be desirable to code a few additional getter methods that permit it to retrieve the data from the outside world. But, wait a minute! You might be wondering what this class has to do with implementing the eager loading pattern, after all. Well, bear with me for the moment and read the following section, where I’m going to add to the class the aforementioned getter methods. Then, once the development of the class has been completed, you’ll see how it fits into the schema imposed by the pattern. Now, click on the link that appears below and keep reading.
blog comments powered by Disqus |
|
|
|
|
|
|
|