apr
2008
Lazy Loading in PHP with __autoload
autoload is one of the magic methods added to PHP in version 5. It creates a very easy way for you to manage all your different class files. Actually, with autoload you don’t need to manage them.
Often you will see in PHP projects files that include the other files needed for that page. You can then end up with a while bunch of require_once calls and so on. This can be quite tedious to maintain and you may not always need all the files.
When you create a new instance of a class PHP checks for it and if it can’t be found the __autoload method is called. It’s passed in one parameter, the name of the class.
<?php function __autoload($class){ require "/path/to/class/files/$class.php"; } $x = new Foo();
Above is a simple example of autoload in action. When a new Foo is created the autoload function requires /path/to/class/files/Foo.php. So with a simple naming convention each class in its own file where the file name is the name of the class (similar to Java) you can easily include files.
This example can be taken slightly further to manage hierarchies of classes...
<?php function __autoload($class){ $class = str_replace('_', '/', $class); $path = "/path/to/class/files/$class.php"; require $path; } $x = new Foo_Bar();
The above code simply replaces all underscores ( _ ) with forward slashes ( / ) before requiring the class. The naming convention changes slightly for this, the class name Foo_Bar would be found in following path:
<?php function __autoload($class){ $class = str_replace('_', '/', $class); $path = "/path/to/class/files/$class.php"; if(file_exists($path)){ require $path; } else { // Error handling here, log it etc. // Exceptions cannot be thrown. } } $x = new Foo_Bar_Fail();
The final example shows the same code again with some optional error checking. It allows you to log errors and so on. However, exceptions cannot be thrown by autoload unless its being called by class_exists. Since this function calls autoload to look for classes. When trying to throw exceptions, PHP runs into a fatal error before its thrown due to the order or autload. This means a fatal error will be triggered as the class can't be found and the exception will vanish.
Following up to this post I plan to do one of spl_autoload soon. With this you can have PHP automatically run its own autoload procedure on include paths. For further reading on this follow the link below. The documentation is a little sparse however.
Enjoy, lazy loading!
Useful links; * Official PHP documentation on __autoload * Official PHP documentation on spl_autoload
Short url - Related tags: design-patterns, lazy-loading, magic-methods, php, spl_autoload