As I stated at the beginning of this series of articles, both lazy and eager loading patterns can be applied in diverse scenarios and contexts with distinct results. It's also valid to mention that there are cases where they’re used by some developers who aren’t completely aware of what they’re really doing. To demonstrate this concept a bit more clearly, take a closer look (and when I say closer, I mean really CLOSER) at the definition of the sample “User” class shown in the previous segment: 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; } }
// get user's first name public function getFirstName() { return $this->fname; }
// get user's last name public function getLastName() { return $this->lname; }
// get user's email public function getEmail() { return $this->email; }
// display user data public function __toString() { return 'First Name: ' . $this->fname . '<br />Last Name: ' . $this->lname . '<br />Email: ' . $this->email; } } If I ever have to make a list of basic classes that I’ve built so far, then the above “User” class would be at the top of that list. So, what’s the unrevealed thing that could be hidden behind its trivial definition? Well, in this case the class assigns default values for its three properties, in case that its constructor gets called with no input arguments. But if you analyze this process in depth, what it’s actually doing is eagerly assigning those values to the properties, regardless of whether or not they’ll be used later. Now, in a situation like this the class would be applying the eager loading pattern to its set of properties, even when in programming jargon this task is commonly known as property initialization. This demonstrates that even a class as basic as “User” also can take advantage of eager loading to prevent possible errors, when attempting to retrieve its properties via its public API. Despite the fact that grasping the implementation of the eager loading pattern within the “User” class is a breeze, it’d be useful to create a script that shows the real benefits of this process. So, in the final section of this article I’m going to build that script for you. To learn more, read the following segment.
blog comments powered by Disqus |
|
|
|
|
|
|
|