Blog Post RSS ?

Blogs » PHP » SmartLoader Reloaded
 

SmartLoader Reloaded

by Maarten Manders

A few months ago I proposed a way to efficiently use __autoload() together with a class indexer. To my surprise, quite some people started using it and provided me with bug reports. I rewrote most of the original code, eliminated all known bugs and have been testing it for the last month. So here’s a new version with some improvements:

  • Added ability to scan include directories, too
  • Using SPL RecursiveDirectoryIterator for the indexer/scanner
  • Optimized SmartLoader::load(). It now takes < 1 ms to complete (with inclusion) on my machine
  • Windows support through DIRECTORY_SEPARATOR constant
  • More information in index file headers, like:
  • 
        * Created by:    /usr/local/php5/lib/php/SmartLoader/SmartLoader.class.php
        * Created at:    Thu, 06 Apr 2006 23:54:48 +0200
        * Scanned:       134 directories and 402 files in 1.15 seconds.
    
  • Fixed various bugs

Backwards compatibility?

Robert Schmelzer dug up the most remarkable bug. As of PHP 5.1.2 this piece of code won’t work anymore:


preg_match_all('/hand/', 'Talk to the hand!', $result = array()));

The $result variable will be empty unless I remove the “= array()”. Why?

Of course, one could argue about how much sense initializing the result as array makes. From my point of view it’s about making the code more readable by showing that I’m passing an empty array to be filled. I suppose Derick, on the other hand, would call it “doing something silly“. ;)

How to use

The best way to use SmartLoader is to put the SVN trunk’s contents into your include directory (don’t forget write access for SmartLoader/indexfiles). After that you can easily set it up in your scripts by adding these two lines:


require('smartloader.php');
SmartLoader::addIncludeDir(dirname(__FILE__).'/../'); /* (or just the document root) */

I strongly recommend prefixing your classes, especially when using the handy include directory scanning or else you’ll get name collisions. Maybe PHP namespaces will solve this problem somewhen.

Share and Enjoy:
  • Digg
  • del.icio.us
  • Facebook
  • Google Bookmarks
  • Ping.fm
  • Twitthis

Related posts:

  1. On $_GET and $_POST Troels Knak-Nielsen offers some thoughts about the naming of $_GET...
  2. How to Use PHP Namespaces, Part 3: Keywords and Autoloading In the final part of his series explaining PHP namespaces,...
  3. Pretty URLs: Pretty Easy! The fourth edition of Build Your Own Database Driven Website...
  4. Techy Treasures #4: What’s inside a dollar function? The $ function is a common feature of all of...
  5. Truthy and Falsy: When All is Not Equal in JavaScript Anything in JavaScript can be considered to be either truthy...

This post has 16 responses so far

Sponsored Links

SitePoint Marketplace

Buy and sell Websites, templates, domain names, hosting, graphics and more.

Follow SitePoint on...