Home arrow PHP arrow Page 2 - Lazy and Eager Loading with Object Properties

Review: using the lazy loader pattern with PHP 5 - PHP

Welcome to the fourth chapter of this series on implementing lazy and eager loading in PHP 5. In five friendly tutorials, this series walks you through the basics of using these powerful approaches for including classes on request in your scripts, and teaches you how to work with these patterns when manipulating properties of a certain class.

TABLE OF CONTENTS:
  1. Lazy and Eager Loading with Object Properties
  2. Review: using the lazy loader pattern with PHP 5
  3. Simple eager loading: examining the user class
  4. Applying eager loading to an instance of the User class
By: Alejandro Gervasio
Rating: starstarstarstarstar / 1
September 23, 2009

print this article
SEARCH DEV SHED

TOOLS YOU CAN USE

advertisement
 

If you still haven’t had the chance to read the preceding installment of this series, where I explained how to use lazy loading for including a sample class into a script only when it was really required, don't worry. In the following lines I reintroduced the full source code corresponding to this example, so you can quickly grasp its underlying logic.

First, here’s the definition of the class that needs to be included on demand. In this case, it's tasked with storing some user-related data through its declared properties:

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 mentioned before, the above “User” class in reality does nothing especially useful, except storing the first and last names, as well as the email address, of a particular user via three properties whose values can be retrieved through the corresponding getter methods.

Now that you understand the internal workings of the previous “User” class, it’s time to show the definition of the loader module, which is responsible for including this class into a calling script on request.

The module in question looks as follows:

// create custom FileNotFoundException exception class

class FileNotFoundException extends Exception {}

 

// create custom ClassNotFoundException exception class

class ClassNotFoundException extends Exception {}

 

spl_autoload_register(array('Loader','load'));

 

// 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.');

}

}

}

Aside from creating a couple of subclasses that extend the default Exception class provided by PHP 5, this loader module defines a basic auoloading mechanism for including a specific class into a script if and only if it’s required by that script.

Of course, if you study closely the rationale that stands behind the loader module, then you’ll realize that it's actually the component that permits it to implement lazy loading in a few simple steps. However, to dissipate your possible doubts, below there’s a script that uses this module for lazily-loading the earlier “User” class:

// create instance of 'User' class only when the script requires it

try {

// create instance of 'User' class

$user = new User();

echo $user;

}

catch (FileNotFoundException $e){

echo $e->getMessage();

exit();

}

 

catch (ClassNotFoundException $e){

 echo $e->getMessage();

exit();

}

There you have it. As the previous code sample shows, the “User” class is only included into the calling script when it’s really required, thanks to the functionality of the loader module shown before.

So far, so good. Now that you realized that applying the lazy loading pattern in PHP 5 is much easier than you might think, it’s time explore other situations where this pattern, and its counterpart, eager loading, can be applied with different levels of success.

It’s quite possible that by the time you looked at the sample “User” class, you noticed that it implements eager loading in a pretty basic way. But, in which part of the class does this take place? Well, the answer to this question is really obvious, but if you need a complete explanation of this mysterious thing, then click on the link below and read the following section.



 
 
>>> More PHP Articles          >>> More By Alejandro Gervasio
 

blog comments powered by Disqus
escort Bursa Bursa escort Antalya eskort
   

PHP ARTICLES

- Hackers Compromise PHP Sites to Launch Attac...
- Red Hat, Zend Form OpenShift PaaS Alliance
- PHP IDE News
- BCD, Zend Extend PHP Partnership
- PHP FAQ Highlight
- PHP Creator Didn't Set Out to Create a Langu...
- PHP Trends Revealed in Zend Study
- PHP: Best Methods for Running Scheduled Jobs
- PHP Array Functions: array_change_key_case
- PHP array_combine Function
- PHP array_chunk Function
- PHP Closures as View Helpers: Lazy-Loading F...
- Using PHP Closures as View Helpers
- PHP File and Operating System Program Execut...
- PHP: Effects of Wrapping Code in Class Const...

Developer Shed Affiliates

 


Dev Shed Tutorial Topics: