Psr4 Class Naming
ID |
php.psr4_class_naming |
Severity |
info |
Remediation Complexity |
trivial |
Remediation Risk |
medium |
Remediation Effort |
low |
Resource |
Naming Convention |
Language |
Php |
Tags |
autoloading, naming_convention |
Description
Reports a class, interface, trait or enum whose name does not match the base name of the file
that declares it, as required by the PSR-0 / PSR-4 autoloading standards. A file Foo.php must
declare exactly one type, named Foo, compared case-sensitively. Any extra top-level type, and
any sole type whose name differs from the file base name, breaks autoloading.
Rationale
PSR-4 maps a fully-qualified class name directly onto a file path, so the autoloader expects the
type App\Foo in Foo.php. A type named differently from its file, or a second type sharing the
file, cannot be found by the standard autoloader and forces a manual require — defeating the
point of autoloading and making the codebase harder to navigate. Because at most one type can
match the file base name, the matching type is left alone and the mismatched or extra types are
flagged. Anonymous classes have no name and are never reported. Files that are not PSR-4
autoloaded are exempt: WordPress-style class-.php / interface-.php / trait-*.php files,
timestamped Laravel migrations under a migrations/ directory, and test files (*Test /
*Tests).
<?php
// File: Order.php
class Order {} // OK — name matches the file base name
class OrderHelper {} // FLAW — extra type in Order.php; belongs in OrderHelper.php
Remediation
Move each type into its own file whose base name matches the type name exactly (case-sensitive),
e.g. place OrderHelper in OrderHelper.php. Rename a sole mismatched type, or its file, so the
two agree.