PHP Namespaces and Autoloaders, Reviewed

Weird Things to Avoid

Using multiple namespaces in one file.

You can use two or more namespaces in one file. Don’t do it:

namespace Foo;
function a() { ... }

namespace Bar;
function a() { ... }

namespace Baz;
function a() { ... }

The autoloader is trying really hard to map namespaces to file paths. Breaking the 1-1 mapping from namespaces to directories would just mess with that.

PSR-0 Underscores

I used the PSR-0 autoloader above, but you should try to hew to the PSR-4 standard.

PSR-4 is just a more restrictive autoloader than PSR-0. PSR-0 was designed to handle underscores in class names, because that’s how classes were named in the past. PSR-4 got rid of the underscores. We’re trying to have a 1-1 map from namespace parts to directories.

PHP allows you to register multiple autoloaders, so you can use both and hand tune one to work with the old classes. Still, for all new code, don’t use underscores in the classnames.

(In production, you typically use the composer tool to generate a classmap, which is an autoloader that maps from the class name to a file. It doesn’t do string manipulations.)

Namespacing Functions

It’s not that namespacing functions is bad, it’s just weird. Most code out there puts a class around everything. If it’s not really OO, just use a static class. This way, the autoloader will work.

There is no autoloader for functions. That means, if you namespaced functions, you’d need to “require” all the function source files before you do anything else.

That’s what we’re trying to avoid!

The only reason to namespace functions is to avoid having them clash with other function names in old libraries that used global function names. Namespacing these old libraries is a handy technique, but it’ll mess up your code.

Leave a Reply