WP Core Handbook > PHP Coding Standards > Naming Conventions suggests the following for naming files with classes:

Class file names should be based on the class name with class-
prepended and the underscores in the class name replaced with hyphens,
for example WP_Error becomes:

class-wp-error.php

While from the wording of the section it’s primarily intended for core use, the coding style overall commonly does (and should in my opinion) apply to third party WP code.

However since core doesn’t support namespaces (PHP 5.2, ugh) this doesn’t account for such case.

What is the practical way to go for it from the perspectives of developer convenience? Support of autoloaders?

I could see multiple alternative ways:

  • ignoring namespace altogether
  • including namespace in file name
  • using namespaces as folder levels
  • using alternate naming scheme altogether, such as PSR

4 s
4

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 Reply

Your email address will not be published. Required fields are marked *