An Object-Oriented Approach to Lazy and Eager Loading in PHP 5

Welcome to the second installment of a series that shows you how to implement lazy and eager loading in PHP 5. Through a strong hands-on approach, this series teaches you how to use these patterns in some typical scenarios. In this way, you’ll grasp their underlying logic and learn quickly how to take advantage of their functionality to speed up your own PHP-based programs.

Learning how to apply the lazy and eager loading design patterns in PHP 5 can have a huge impact in the performance of your web-based applications, especially if they rely on objects that are used for interacting with one or multiple database tables. Therefore, if you’re interested in learning the key concepts that surround the implementation of these powerful behavioral patterns, then don’t hesitate anymore and start reading right now!

And now that you know what to expect from this set of articles, it’s time to refresh the topics that were discussed in the previous one. To summarize, in that first part of the series I developed an example to demonstrate how to use eager loading pattern in conjunction with a sample class that stored information about some fictional users through its properties.

The example was comprised of a single script that included the class at the very beginning of its execution, and created an instance of this class, even when this instance wasn’t specifically requested by the program. In programming jargon, this process is commonly known as eager inclusion of a class (or eager loading, naturally). When applied in a clever way, it can help make certain applications run faster.

However, the example that I just described above used a mixture of procedural and object-oriented code to perform the corresponding eager loading process, which isn’t very efficient. Thus, in this second chapter of the series I’m going to modify this example by employing a strict object-oriented approach.

Now, let’s leave the preliminaries behind us and continue learning more about the eager loading pattern in PHP 5. Let’s get started!

{mospagebreak title=Review: eager loading in PHP 5}

The eager loading pattern can be used in cases ranging from the inclusion of dependencies to the instantiation of classes. Nevertheless, it’d be useful to recall the example created in the previous installment of the series, which demonstrated how to apply the pattern to loading a class that stored user-related data.

That being said, here’s the definition of the 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;

}

}

 

// 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;

}

}

As I explained before, this class does nothing particularly special. It can be used for easily saving information about some users, such as their first and last names, and their email addresses as well, to its private properties.

Obviously, building a class like this is only for example purposes, so let me go one step further and show you a script that includes the class using the eager loading pattern. Here it is:

<?php

require_once ‘user.php’

/* rest of script code

goes here

*/

// create instance of ‘User’ class

$user = new User();

// display user data

echo $user;

?>

If you’re wondering about the point of creating the above script, again I have to say that it’s for demonstrative purposes. However, don’t judge me harshly; pay close attention to the things happening behind the scenes within the script. As you can see, the previous "User" class is directly loaded via a regular PHP include, without taking into account whether or not an instance of it will be required by the program, something that only occurs at the end.

Though it may look rather primitive, this code sample shows a simple use of the eager loading pattern when including classes into a certain script. As you may have realized, in this specific case the pattern is detrimental to the script’s performance, but like I said in the introduction of this series, there are cases when eager loading can be of great help, particularly when used for performing fewer SQL queries.

However, for the moment that topic is out of the scope of this article. Thus, now that you’ve hopefully understood how the previous example works, it’s time to dig deeper into the usage of eager loading in PHP 5.

As you may have noticed, the script that eagerly loads the sample "User" class utilizes a mix of procedural and object-oriented code to implement the pattern. We can improve this by creating a class responsible for including that class via a static method.

Therefore, in the upcoming section I’m going to define a basic loader class that will avoid explicitly calling any PHP "require/require_once()" function when including a specified class.

To learn the full details of how this class will be constructed, go ahead and read the following segment. It’s only one click away.

{mospagebreak title=Building a basic loader class}

As I said in the section that you just read, I’d like to provide you with an example that shows how to eagerly include the previous "User" class by using a stricter object-oriented approach. To accomplish this, I’ll code a simple loader class whose main goal will be statically including a specified file into a given script.

The complete definition of this brand new loader mechanism, along with a couple of custom exception classes, is shown below. Look at them, please:

// create custom FileNotFoundException exception class

class FileNotFoundException extends Exception {}

 

// create custom ClassNotFoundException exception class

class ClassNotFoundException extends Exception {}

 

// define ‘Loader’ class

class Loader {

 

public static function load($class)

{

if (class_exists($class, FALSE))

{

return;

}

$file = $class . ‘.php’;

if(!file_exists($file))

{

throw new FileNotFoundException(‘File ‘ . $file . ‘ not found.’);

}

require $file;

unset($file);

if (!class_exists($class, FALSE))

{

eval(‘class ‘ . $class . ‘{}’);

throw new ClassNotFoundException(‘Class ‘ . $class . ‘ not found.’);

 }

}

}

As depicted above, the "Loader" class is comprised of a single static method called "load()," which implements the logic required to include the definition of a specified class into a calling script. Also, I added a couple of exception subclasses to handle more specifically any errors that might arise when performing the inclusion process.

So far, so good. At this point, I’m pretty sure that you already grasped the underlying logic of the above "Loader" class, right? Then it’s time to build a script that uses this loader module to eagerly include the sample "User" class.

Want to see how this will be done? Click on the link that appears below and read the next section.

{mospagebreak title=Using the Loader class in a sample script}

Having created a class that’s capable of loading other classes via its static "load()" method, it’s time to use it, right? To do so, below I coded another script that utilizes this loader module to eagerly include the previous "User" class.

Now, study the following code fragment:

try {

// load eagerly ‘User’ class

Loader::load(‘user’);

/*

rest of logic goes here

*/

// create instance of ‘User’ class

$user = new User(‘Mary’, ‘Smith’, ‘mary@domain.com’);

echo $user;

}

catch (FileNotFoundException $e){

echo $e->getMessage();

exit();

}

 

catch (ClassNotFoundException $e){

 echo $e->getMessage();

exit();

}

Here you have it. Through a few lines of strict object-based code it was feasible to successfully apply the eager loading pattern. As seen above, a couple of "catch()" blocks are used to intercept specific exceptions that might arise when including the file that contains the "User" class, but of course it’s possible to remove this error handling mechanism if you don’t want to deal with it.

Finally, I encourage you to edit all the code samples shown in this tutorial, so you can arm yourself with a better understanding of the eager loading pattern in PHP 5.

Final thoughts

In this second chapter of the series, I showed how to implement the eager loading pattern in PHP 5 by using a stricter object-based approach. The example that you saw a few lines ago applied this pattern to include a user-related class and create an instance of it without receiving an explicit request to do so, which show that the benefits of using this or any other pattern depend strongly on the development context.

In the upcoming article, I’m going to explain how to apply the lazy loading pattern with the same "User" class. Thus, if you wish to learn the full details of this process, then don’t miss the next part!

[gp-comments width="770" linklove="off" ]

chat sex hikayeleri Ensest hikaye