phpphpcspsr-12

Is there a way to break down a namespace in PHP?


I found myself looking on the internet for someone who has already answered it, but I can't find any.

I was cleaning up some code with a strict PSR12 standard, and I found this issue with namespace getting longer than the configured 80 characters (which is our soft limit, which created a warning).

So far I have found a proper way of writing readable code while staying well within the 80 lines, no matter how long the names were. But for the namespace I haven't. Many of our namespace declarations look like this:

namespace CompanyName\ProjectName\Domain\SubClasification\Clasification\ModuleName;

They can get quite long, especially since many on my colleagues like very long class names, so I would like to know if there are ways to fit the namespace declaration on multiple lines?


Solution

  • You can split the namespace on the separator character, so this is valid syntax:

    namespace CompanyName
        \ProjectName
        \Domain
        \SubClasification
        \Clasification
        \ModuleName;
    

    Alternatively, you can tell PHPCS to ignore the next line:

    // phpcs:ignore
    namespace CompanyName\ProjectName\Domain\SubClasification\Clasification\ModuleName;
    

    You could also perhaps create a custom PHPCS sniff that extends the existing line length sniff but excludes namespace lines.

    [EDIT] Note, it looks like the ability to multi-line the namespace may be going away in PHP 8: https://3v4l.org/IWbe1