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.

Tuesday, May 8, 2012

Doing a 360 on Grid 960

I've never been a fan of CSS frameworks; They just seem unnecessary to me. Every project can benefit from a reset.css file and maybe basic typography styles, but a whole framework? Meh.

Then I read an excellent argument in favor of grid-layout frameworks in some book which I've since forgotten the name of and changed my mind (a tremendous feat indeed). I decided I'd make use of a grid-layout framework in my next project.

I chose Grid 960 for the project since that was the one mentioned in the book, I had heard about it before, and it seemed to me the most mature and stable. My experiences with Grid 960 weren't bad per se... I mean, it didn't sour me back to my original mindset... but a few points will have me looking for another framework.

  1. The extra markup required is basically reminiscent of tables. Instead of <tr> or <td> though now you've got <div class="container_12"> and <div class="grid_3">.
  2. Borders, margins, and padding will throw your grids off. While it makes sense and is ultimately unavoidable, it highlights the fact grid-systems are not necessarily as intuitive as they claim to be.
  3. I found 960px still a bit wide. More screen-real estate is available than there was a few years ago, but people don't necessarily view sites full screen like they did back in the 800x600 days.
  4. Grid 960 isn't scalable. I'm not talking about "responsive web design" here, rather just using ems or rems instead of pxs so things can scale properly.

Researching beyond 960 I saw there are few fluid and responsive ones. And I saw a 1KB framework which was cool. It lacked push/pull functionality, but would be sufficient for most of my work I think.

So 960 wasn't my cup of tea, but I haven't given up on grid-frameworks yet. Maybe I'll find something more to my liking for my next project... or even roll my own.

Friday, May 4, 2012

Are Coding Standards Futile?

Unless the visual layout of a program's code affects its execution, there will always be programmers who circumvent the established coding standards. I admit, I've done it myself from time to time. There's no scientific survey that such standards really reduce cognitive friction when reading someone else's code as far as I know, and aesthetic matters are generally subjective. Make the argument for tabs over spaces until you're blue in the face; someone will just come along touting the benefits of spaces.

I warned achieving a consensus on PHP Coding Standards as PSR-1 would be difficult and that the group's efforts would be better spent discussing more "meatier" topics, such as object caching. Two months later, the proposal failed to garner enough votes for a simple majority and has now been split.

And let's not forget the "Beat Up on Crockford" festival over bootstrap and JSMin. His comments were a bit harsh, yes... but then again he only made two comments in the entire (quite lengthy) discussion and ended up immortalized in the (admittedly funny) Dangerous Punctuation.

Novelists don't all write in the same style; noting the formatting in a section of code might give a heads up on who wrote it or insight into the coder's way of thinking. Maybe it's a clue as to who we can go to for help when something doesn't work. Weak arguments, sure. But maybe so is "consistency breeds success" when applied to code formatting.

Most coding standards seem to target only low-hanging fruit anyway: capitalize something this way, place your braces in this manner, space something that way, etc. None of that really matters, does it? Standards that enforce good architectural design, specific interoperability concerns, etc. have more merit. After all, standards should help make things work, not squash creativity. And if Joe Programmer's self-expression manifests itself as 5-space indenting, who am I to judge?