Deferring Class Property Creation with Lazy Loading

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 you may know as a PHP programmer, one of the most important facets that must be tackled during the development of a web application is properly establishing the way that its resources will be managed. While there are many factors involved in this process that will affect, both directly and indirectly, the end performance of a certain program, it’s possible to use well-trusted approaches to define how "early" a specific resource will be loaded by the program in question.

In software programming, there are two design patterns that permit you to achieve this definition procedure with relative ease, popularly known as lazy and eager loading. As you may have guessed, in the first case loading a determined resource will be delayed or deferred until an application (or a part of it) actually requests it, while in the last case the resource will be loaded as soon as possible, regardless of whether or not it’s required by the application.

In this particular context, the term "resource" references anything suitable to use within a PHP-driven program, ranging from classes to objects, configuration files, database result sets and so forth. How much success you can achieve when applying the aforementioned patterns will depend strongly on the type of resource you’re handling.

However, if you’ve been a loyal follower of this article series and have already read all of the tutorials that precede this one, then it’s probable that at this point you’re familiar with using eager and easy loading in PHP 5. In those articles I explained how to apply these patterns when including a class within a script, as well as when declaring and assigning values to its properties.

This last scenario was recreated in the last article, where I showed how a class that stored user-related data eagerly assigned default values to its declared properties, showing that eager loading can be used in many different cases.

Nevertheless, if it was possible to eagerly handle properties of a class, then in theory it would also be feasible to invert the process and manipulate those properties in a lazy fashion, right? Well, that’s true, and in this final chapter of this series I’m going to show you through some code samples how to accomplish this with minor hassles.

Now start reading this last part of the series!

{mospagebreak title=Review: eagerly loading properties of a class}

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.

{mospagebreak title=Applying lazy loading to class properties}

In order to illustrate how lazy loading can also be used successfully with the properties of a class, I’m going to redefine the previous "User" class so it can create properties dynamically. 

Having explained this, take a look at the brand new definition of "User," which now is as follows:

class User

{

private $data = array();

 

// constructor (not implemented)

public function __construct(){}

 

// implement ‘__set()’ magic method

 public function __set($name, $value)

{

if (!isset($this->data[$name]))

{

$this->data[$name] = $value;

}

}

 

// implement ‘__get()’ magic method

public function __get($name)

{

if (isset($this->data[$name]))

{

return $this->data[$name];

}

}

 

// implement ‘__toString()’ magic method

public function __toString()

{

$str = ”;

foreach ($this->data as $property => $value)

{

$str .= ‘Property: ‘ . $property . ‘ Value: ‘ . $value . ‘<br />’;

}

return $str;

}

}

For obvious reasons, building a class that’s only comprised of a few magic PHP 5 methods isn’t a good thing at all, but given that I plan to use it for demonstrative purposes I recommend that you study its signature closely to grasp its underlying logic.

As shown above, apart from implementing the already familiar "__toString()" method, the class does the same thing with the complementary "__set()" and "__get()" tandem, which permits it to dynamically create and retrieve undeclared properties, a process commonly known in PHP 5 as property overloading.

It’s quite possible that at this moment you’re wondering what the point is in implementing the "__set()" and "__get()" magic methods. Considering that they can be used for creating and fetching properties on request, then it’d be correct to say that those properties could be brought to life in a true "lazy" way. That’s a quite interesting concept, isn’t it?

Of course, in most cases using property overloading can make the code of classes difficult to read and harder to follow. However, in this particular example this approach comes in handy for demonstrating how easy it is to use lazy loading when creating the properties of a basic class.

But if you’re like me, you’ll want to see an example that shows how to work with the modified version of the previous "User" class. Therefore, in the course of the section to come I’m going to build a simple script that will lazily assign properties to that class.

To see how this script will be developed, go ahead and read the following segment. It’s only one click away.

{mospagebreak title=Building a final script}

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 = ‘alejandro@domain.com’;

// display user data

echo $user;

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.

Final thoughts

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.

See you in the next PHP development tutorial!

[gp-comments width="770" linklove="off" ]
antalya escort bayan antalya escort bayan