Clean (PHP) Code: Namespaces
By: Travis Weston
Tags: Namespaces, Php Developers, Web Development, Clean Code, PHP

I’m showing my age a little here, but I’ve been using PHP since before PHP had namespaces.

I joined PHP when class names doubled as pseudo-namespaces. Back when we had class names that looked like this:

class Zend_Pdf_Element_Reference_Context{} $pdfContext = new Zend_Pdf_Element_Reference_Context();

Enter Namespaces

On the outside, PHP namespaces work very similarly to the old pseudo-namespaces. You still include the full namespace at the top of your file when calling it, but now you only need to remember the final class name — or the name that you tell your code to call the namespaced class as.

use App\Http\Client as HttpClient; $client = new HttpClient();

Like so.

It shrinks the code, and removes a lot of unnecessary information from the body of your content, putting it in the header where it belongs. Someone reading your code isn’t likely to care where HttpClient came from. They want to know what that object does.

But for those that actually do need to know where to find the HttpClient code, they know where to look to find that information.

Challenges of Namespaces

There are some obvious potential issues, however. Like anything else, there are no foolproof methods. Namespaces don’t guarantee clean code, they simply make it much easier to achieve.

For that reason, I have a list of suggestions for how to maintain the cleanliness of your code when using Namespaces.

Use Autoloading

I was going to put this as a note, but it deserves to be it’s own section here. Autoloading combined with Namespaces is almost a no brainer. Autoloading should be almost the first thing you setup in any new project, and in doing so, you should be designing how you’re going to layout your project with it.

I suggest the usage of PSR-4 Autoloading, which ties your namespaces to your folder structure. PSR-4 is a tried and true standard in PHP, and will allow most developers entering your project to at least understand where to find files, just by looking at the namespaces.

Clean code is more than just what’s written in the files. Much like a clean room lends itself to a clean mind, a clean folder structure lends itself to clean code.

Limit the number of use statements

The use statement is how you tell PHP that you are using a specific namespace in your code. Use statement clutter is also easily one of the first issues you will come across in modern PHP projects, due to the prevalence of code sharing and Composer.

The problem is, code that contains a lot of use statements is a code smell. That smell is almost always indicating that file is in violation of the single responsibility principle.

If you have a lot of use statements at the top of your file, take the time to look over the code. Are there any groups of methods that seem to team up together that might be able to be pulled out into their own class?

Or maybe there is a group of dependencies that your class seems to always use together. Consider pulling those into their own class, and building an abstraction layer between your class and those dependencies.

Be explicit about your use statements

This one goes against the language, but it makes for more readable code. PHP allows you to use classes in the same namespace without adding a use statement for these classes.

Don’t do that.

If you use a class, even if that class is in the same namespace, add a use statement to the top of your file. This way, you can see all that file’s dependencies at a glance.

Without that use statement, you have a hidden dependency. Sure, your IDE might pick up on it, but my rule of thumb is if I can’t read your code easily when it’s printed out on a conference room table, then it’s not clean enough.

Group your dependencies by package

When you’re listing your dependencies in your header, group your use statements by the package and sub-package. This way, if I’m working on a dependency of your class, I can see which files you depend on at a glance.

Along with making sure that dependencies are grouped together, you should add a single line break between each package. By that I mean final package, so App\Foo\Bar would be a different package than App\Foo or App\Foo\Baz and should be logically separated from each.

You’re probably noticing a pattern with these suggestions. We want namespaces to get out of our way, and play their role when they need to, but then get back out of our way as quickly as possible.

In that same vein, let’s move on to the next suggestion.

Sort use statements in alphabetical order

If you follow this suggestion, then you will naturally end up grouping packages together like I suggested above. The only difference in the above suggestion would be the line break. That’s a simple edit to make.

Now, one thing you will have to do is make sure that you’re going through your files and cleaning up your header, since IDEs like PhpStorm will add your use statements for you.

This is a great convenience, and should be used during the coding phase. But as soon as you have your tests green, and you’re in the refactoring stage, check your dependency list.

Logically separate your namespaces

Namespaces are here for a reason. You should be using them for that reason. What is it? To logically separate your code into packages that are reusable, or modular.

One common thing that I see is developers using namespaces, but putting everything in a single master namespace. There can be good reasons to do that, but it largely depends on the situation.

If you’re working on a project that will be distributed, it’s better to nest all of your namespaces under a master project package name. But if you’re running in a framework like Laravel, for instance, which uses multiple namespaces at the framework level, it’s better to be logical about where you store things.

What do I mean?

Where do you store a custom Faker in Laravel? A cursory search of Google finds the majority of people suggesting two things: Anonymous classes, and storing fakers in App\Fakers .

The faker package, however, is only available on development — by default. So what you have, then, are development dependencies cluttering your production application code.

Wouldn’t it be better to instead create your faker in Tests\Fakers and your service provider in Tests\Providers ?

I think so.

So what now?

Go forth and namespace!

Seriously, as PHP matures and grows, namespaces will only become more necessary to use, and use properly. Take the advice above, and implement it in your projects.

You’re likely do many of these suggestions in the course of your day anyway. It’s not much effort to implement the rest.