Baylor Rae'

$ cat "baylor rae's thoughts" > index.php

Lazy Loading with PHP

December 23, 2011 | Baylor Rae' 2 Comments

I've been looking through a lot of PHP projects on GitHub lately and I keep seeing people including all their classes on launch. And unfortunately it's the reason I decide not to use their code.

What is Lazy Loading

Lazy loading it a pattern of only including classes when they are needed. And fortunately enough PHP makes it super easy to implement.

<?php

function __autoload($class_name) {

  // looks for 'classes/user.php';
  $file = 'classes/' . strtolower($class_name) . '.php';
  if( file_exists($file) )
    require_once $file;
}

/*
    Because the User class has not been included on this page
    PHP will run `__autoload` and try to include it automatically
*/
$user = new User;

// do stuff with $user

?>

I realize that I could have used require 'classes/user.php';. But as the application grows and I have more classes I don't have to worry about including each file. I used this same pattern in my Huck PHP Testing Framework.

In my framework my autoload setup worked like this though.

<?php

// Allows multiple __autoload stacks
// and keeps autoloader in Huck class
spl_autoload_register(array('Huck', 'autoload'));

class Huck {

    public static function autoload($class_name) {
        if( substr($class_name, 0, 5) === 'Huck_' ) {

            $file = dirname(__FILE__) . '/' . substr($class_name, 5) . '.php';
            if( file_exists($file) )
                require_once $file;
        }
    }

}
?>

This is my preferred way of autoloading because it allows multiple autoloaders to be registered. This way if someone includes Huck in their application that already has an __autoload in place, mine doesn't override it.

The substr() function is called to make sure the $class_name starts with Huck_. The second time I call it I remove Huck_ so I get whatever is left.

Checkout the Huck Framework to see how my file structure and autoloader.

2 Responses to Lazy Loading with PHP

  1. Rhythmer said

    This is great information. Thanks for the article. Keep up the great work.

  2. Martin said

    Hey! Nice little article!!

Leave a Reply

Your email address will not be published. Required fields are marked *

*

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>