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, 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.

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.


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

    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])

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

  3. By the way, the autoloader function itself is not PSR save ! I just asked a similar question on stack overflow:

    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.

  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:
    And to write the shortest PSR-0 compliant autoloader :
    Obviously not compatilbe with PSR-1 and PSR-2...


Post a Comment

Popular posts from this blog

Geolocation Search

Services that allow users to identify nearby points of interest continue to grow in popularity. I'm sure we're all familiar with social websites that let you search for the profiles of people near a postal code, or mobile applications that use geolocation to identify Thai restaurants within walking distance. It's surprisingly simple to implement such functionality, and in this post I will discuss how to do so.

The first step is to obtain the latitude and longitude coordinates of any locations you want to make searchable. In the restaurant scenario, you'd want the latitude and longitude of each eatery. In the social website scenario, you'd want to obtain a list of postal codes with their centroid latitude and longitude.

In general, postal code-based geolocation is a bad idea; their boundaries rarely form simple polygons, the area they cover vary in size, and are subject to change based on the whims of the postal service. But many times we find ourselves stuck on a c…

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 ShouldersComposition doesn’t happen in a vacuum. Bach was f…

Creepy JavaScript Tracking

I recently began allergy shots so my new Monday morning routine includes me sitting in a doctor's office for 30 minutes (I must wait after receiving the shots and be checked by a nurse to make sure there was no reaction). With nothing else better to do while I waited last week, I started playing around with some JavaScript. This is what I came up with:
<html> <head> <title>Test</title> <script type="text/javascript"> window.onload = function () { var mX = 0,  mY = 0, sX = 0,  sY = 0, queue = [], interval = 200, recIntv = null, playIntv = null, b = document.body, de = document.documentElement, cursor = document.getElementById("cursor"), record = document.getElementById("record"), play = document.getElementById("play"); window.onmousemove = function (e) { e = e || window.event; if (e.pageX || e.pageY) { …