How to name files of namespaced classes?

First, ignore the class- prefix. This comes from WordPress’ pure procedural code approach, classes are used as containers for procedural code, not for real objects, and most files do not contain classes at all or classes and other code together. It doesn’t make sense when all of your files contain just one class and nothing else.
If you would follow that pattern you would have to use interface-foo.php and trait-bar.php. That doesn’t just look ridiculous, it makes the auto-loading harder than necessary.

The easiest way to separate namespaces and class/interface/trait names is (by my experience) assigning namespaces to directory names and class names to file names. This makes it very easy to map the requested class to a given file structure in the auto-loader: Just convert \ to /, append .php and load the file.

This makes it also easy to cache the look-ups: for every directory/namespace you can fetch all existing files the first time that directory is requested, and for later calls you can take the reuse that list of file names without asking for file_exists() every time.

Leave a Comment