In the introduction, I mentioned that it's possible to implement lazy loading with the properties of a class. However, before I start explaining how to do that, it'd be useful to briefly recall the example developed in the previous article. It demonstrated how to perform the inverse process, that is, apply the eager loading pattern to those properties. Having explained that, here's the complete definition of the class that eagerly declares its properties. Take a look at it, please: 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; } } In this specific case, the above "User" class does nothing especially useful or interesting, except for the fact that it utilizes its three declared properties for storing data on a particular user. However, it also transparently implements the eager loading pattern. Think of this process very carefully: not only does the class declare the properties regardless of whether or not they're requested later, but it eagerly assigns some values to them. Naturally, there are valid reasons to perform this eager assignment that have to do with promoting good programming habits rather than with the eager loading pattern itself. However, the script below shows that eager loading makes a lot of sense in this case: require_once 'user.php' // create instance of 'User' class $user = new User(); // display user data echo $user; Simple to code and illustrative, right? As you can see, a direct call to the "__toString()" method of "User" will produce a non-empty output, which demonstrates how to apply eager loading to properties of a basic class. So far, so good. Now that you hopefully understood how the previous example functions, it's time to continue learning a few more things regarding the application of lazy and eager loading patterns in PHP 5. Thus, as I stated in the introduction, in the following lines I'm going to show you how to use lazy loading for creating on the fly properties of a class. This will be a no-brainer process, believe me. Now, to find out more on this topic, click on the link that appears below and keep reading.
blog comments powered by Disqus |
|
|
|
|
|
|
|