Does PSR-12 say anything about the way how namespace imports and aliasing should be grouped and sorted?

1.1k views Asked by At

I'm working on a code quality automation with phpmd, phpcs and phpcpd tools. The code sniffer has been set to --standard=PSR12.

I was unable to find any details or recommendations in terms of the way how namespace imports and aliases should be defined:

  • grouping with curly brackets or defining each one in a separate way (which at the moment is my biased suggestion)
  • A-Z sorting

Eg:

use Foo\Bar\{ Lorem, Ipsum, Dolor };

vs:

use Foo\Bar\Dolor;
use Foo\Bar\Ipsum;
use Foo\Bar\Lorem;

If there's no standard recommendation I'm going to establish internal rule within my team, but if there is any, I'm happy to obey it.

1

There are 1 answers

0
PatricNox On

There is a couple of rules regarding the namespaces, but none who explicitly calls for the order. However, this is stated regarding the depth when declaring them:

Compound namespaces with a depth of more than two MUST NOT be used. Therefore the following is the maximum compounding depth allowed:

use Vendor\Package\SomeNamespace\{
    SubnamespaceOne\ClassA,
    SubnamespaceOne\ClassB,
    SubnamespaceTwo\ClassY,
    ClassZ,
};

And the following would not be allowed:

use Vendor\Package\SomeNamespace\{
    SubnamespaceOne\AnotherNamespace\ClassA,
    SubnamespaceOne\ClassB,
    ClassZ,
};

For a general rule, if it's not explicitly stated, then there is no standard. Either works.

You can read more about the existing rules here:

https://www.php-fig.org/psr/psr-12/