To keep this article as straightforward as possible, I will not explain how to use Composer autoloader or how to manage WordPress Coding Standards (by the way, about managing WordPress Coding Standards with Composer you can read here).
The goal of the present article is to tell how I fix an annoying incompatibility between the PSR-4 and WordPress Coding Standards that I came across.
You must know that to use Composer Autoloader, we must follow the PSR-4, so in our composer.json, we need to define something like that:
"autoload": {
"psr-4": {
"MyApp\\": "myapp/"
}
}
The namespaces and class names must follow this example.
You also should know that while working with WordPress projects, it's a good practice to follow the WordPress Coding Standards.
However, the WordPress Coding standards "do not like" the PSR-4 structure and the PHPCS will display an annoying error:
'Class file names should be based on the class name with "class-" prepended. Expected class-somethings.php, but found Something.php'.
If we fix the names for please WordPress Standards, Composer will not find the classes and it will trigger PHP errors🤡.
How to fix that?
If we do not use the PSR-4 structure, the Composer Autoloader simply will not work and, well, autoload is very helpful for several reasons like:
Increase our productivity;
Keep the code cleaner as we don't need to write a bunch of require/include statements;
Also helps to avoid errors (in case we forget to require something).
So, the Composer autoload is a must-have. The solution I am using nowadays is to tell the WordPress Standards: "Sorry, I really like you, but I choose PSR-4 instead and I will have to ignore some of your pieces of advice".
To tell WordPress to ignore the class names requirement, I edit the .phpcs.xml file. In the .phpcs.xml where we can enable custom rules per project and include add or subtract some rules.
In this particular case, what we want to do is to hide the error that says the class filenames are wrong. We’ll add a simple statement to tell PHPCS to ignore the filename standard, the <exclude name="WordPress.Files.FileName" />
In the .phpcs.xml file, in the WordPress rule, you need to add:
<rule ref="WordPress">
<!-- PSR4 -->
<exclude name="WordPress.Files.FileName" />
</rule>
This way, the annoying error "'Class file names should be based on the class name with "class-" prepended. Expected class-somethings.php, but found Something.php'" will disappear.
You can also see a complete example .phpcs.xml file in this Gist for a better understanding.
If it was useful for you, please let me know in the comments, other approaches are welcomed too :)
Top comments (0)