1

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.

halfer
  • 19,824
  • 17
  • 99
  • 186
Matt Komarnicki
  • 5,198
  • 7
  • 40
  • 92
  • If it's not mentioned in their code standard guide (which you've linked to), then they don't have an opinion about it. – M. Eriksson Sep 18 '20 at 11:16
  • You could make it a rule in your team that all PHP files should be reformatted using automated tools (e.g. PhpStorm), which should satisfy PSR-12. A linter could probably check that too - I wouldn't see any value in going above and beyond that. – halfer Sep 19 '20 at 13:02

1 Answers1

4

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/

PatricNox
  • 3,306
  • 1
  • 17
  • 25