Saturday, May 19, 2012

Writing a Minimal PSR-0 Autoloader

An excellent overview of autoloading in PHP and the PSR-0 standard was written by Hari K T over at PHPMaster.com, and it's definitely worth the read. But maybe you don't like some of the bloated, heavier autoloader offerings provided by various PHP frameworks, or maybe you just like to roll your own solutions. Is it possible to roll your own minimal loader and still be compliant?

First, let's look at what PSR-0 mandates, taken directly from the standards document on GitHub:

  • A fully-qualified namespace and class must have the following structure \<Vendor Name>\(<Namespace>\)*<Class Name>
  • Each namespace must have a top-level namespace ("Vendor Name").
  • Each namespace can have as many sub-namespaces as it wishes.
  • Each namespace separator is converted to a DIRECTORY_SEPARATOR when loading from the file system.
  • Each "_" character in the CLASS NAME is converted to a DIRECTORY_SEPARATOR. The "_" character has no special meaning in the namespace.
  • The fully-qualified namespace and class is suffixed with ".php" when loading from the file system. Alphabetic characters in vendor names, namespaces, and class names may be of any combination of lower case and upper case.

The first two and the last points are aimed at module/library authors, and the third point is of little consequence. The remaining three are the important points relevant to writing the autoloading mechanism. Of course standards have to be wordy by their very nature, but if you boil the relevant mandates down they essentially say the following: “replace namespace separators and class-name underscores with a directory separator and append a .php suffix.”

The standard doesn't describe what support functionality must be provided by a PSR-0 compliant autoloader (registration methods, configuration options, etc.). If it can automatically find a class definition in the \<Vendor Name>\(<Namespace>\) pattern, then it's PSR-0 compliant. Furthermore, it doesn't specify the parent directory for <Vendor Name>. The extra “fluff” of most autoloader implementations is convenient if you need to specify the location via code, but most of the times unnecessary if you simply use a directory already within PHP's include path.

With modern namespacing support in in PHP, it's probably not necessary to encapsulate the logic as a class, like most libraries/frameworks do, either. A single function can perform the necessary transformations on a class path and be namespaced properly so it doesn't pollute the global namespace. Instead of creating an instance of an autoloader object and then invoking the instances register() method, one can simply register a function directly with spl_autoload_register().

Or if you want to be even more minimal, you can register an anonymous function with spl_autoload_register(). Put the code in an include file, include that file, and you have no-muss-no-fuss PSR-0 autoloading instantly at your disposal.

<?php
spl_autoload_register(function ($classname) {
    $classname = ltrim($classname, "\\");
    preg_match('/^(.+)?([^\\\\]+)$/U', $classname, $match);
    $classname = str_replace("\\", "/", $match[1])
        . str_replace(["\\", "_"], "/", $match[2])
        . ".php";
    include_once $classname;
});

The magic here is in the regex which splits the incoming name into its constituent parts; the class name will always be in $match[2], and $match[1] the namespace name which may or may not be an empty string. It's necessary to identify the parts because the underscore has no special meaning in the namespace portion making a blind replace on underscores and backslashes incorrect.

Oh, and before you start jumping all over me about DIRECTORY_SEPARATOR, I'd like to point out that a hard-coded slash is equivalent for the purpose here. From the PHP manual:

On Windows, both slash (/) and backslash (\) are used as directory separator character. In other environments, it is the forward slash (/).

So YES, it is possible to write a minimal and elegant PSR-0 compliant autoloader. The only extra requirement is that the <Vendor Name> directories already be in PHP's include path to negate the need for additional path registering functions, which I would argue is good practice anyway.

Perhaps someday the group could sponsor something that mandates the path requirement (and maybe name it PSR-0a)?

Of course, maybe I'm just crazy.

Special thanks to Graham Christensen for his efforts in proofing my concept.

6 comments:

  1. Thank you.
    But there's a problem with 'str_replace(["\\", "_"], "/", $match[2])'.
    Should be 'str_replace("\\", "_", "/", $match[2])'

    ReplyDelete
    Replies
    1. This *is* a problem in php 5.3 and below. If you are not using PHP 5.4, then it needs to be like this:

      str_replace(array("\\", "_"), "/", $match[2])

      Delete
  2. Ok, forget my previous comment.
    I was all wrong.

    ReplyDelete
  3. By the way, the autoloader function itself is not PSR save ! I just asked a similar question on stack overflow: http://stackoverflow.com/questions/12332090/how-to-write-this-autoloader-psr-0-1-2-save

    ReplyDelete
    Replies
    1. Thanks for the comment, Chris! The functionality should still be PSR0 compliant; the rest is just style. Reformatting the code should bring you PSR1/2 compliance if that's what you're after.

      Delete
  4. Thanks a lot for this nice minimal autoloader !

    I like short code but not a huge fan of PSR-1 and PSR-2 ;)

    It inspired me to answerto Stackoverflow question:
    http://stackoverflow.com/a/14831482/1154106
    And to write the shortest PSR-0 compliant autoloader :
    https://gist.github.com/adriengibrat/4761717
    Obviously not compatilbe with PSR-1 and PSR-2...

    ReplyDelete