Skip to main content

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.

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

Post a Comment

Popular posts from this blog

Composing Music with PHP

I’m not an expert on probability theory, artificial intelligence, and machine learning. And even my Music 201 class from years ago has been long forgotten. But if you’ll indulge me for the next 10 minutes, I think you’ll find that even just a little knowledge can yield impressive results if creatively woven together. I’d like to share with you how to teach PHP to compose music. Here’s an example: You’re looking at a melody generated by PHP. It’s not the most memorable, but it’s not unpleasant either. And surprisingly, the code to generate such sequences is rather brief. So what’s going on? The script calculates a probability map of melodic intervals and applies a Markov process to generate a new sequence. In friendlier terms, musical data is analyzed by a script to learn which intervals make up pleasing melodies. It then creates a new composition by selecting pitches based on the possibilities it’s observed. . Standing on Shoulders Composition doesn’t happen in a vacuum. Bach wa...

Learning Prolog

I'm not quite sure exactly I was searching for, but somehow I serendipitously stumbled upon the site learnprolognow.org a few months ago. It's the home for an introductory Prolog programming course. Logic programming offers an interesting way to think about your problems; I've been doing so much procedural and object-oriented programming in the past decade that it really took effort to think at a higher level! I found the most interesting features to be definite clause grammars (DCG), and unification. Difference lists are very powerful and Prolog's DCG syntax makes it easy to work with them. Specifying a grammar such as: s(s(NP,VP)) --> np(NP,X,Y,subject), vp(VP,X,Y). np(np(DET,NBAR,PP),X,Y,_) --> det(DET,X), nbar(NBAR,X,Y), pp(PP). np(np(DET,NBAR),X,Y,_) --> det(DET,X), nbar(NBAR,X,Y). np(np(PRO),X,Y,Z) --> pro(PRO,X,Y,Z). vp(vp(V),X,Y) --> v(V,X,Y). vp(vp(V,NP),X,Y) --> v(V,X,Y), np(NP,_,_,object). nbar(nbar(JP),X,3) --> jp(JP,X). pp(pp(PREP,N...