phpnaming-conventionsnamingpsr-4psr-2

PHP Namespace Class Naming Convention


I currently follow PSR-2 and PSR-4. I'm running into a small dilemma when trying to name a few classes. Here's an example.

I have a base REST client, \Vendor\RestClient\AbstractClient. I have two implementations of this Abstract Client:

Is the naming of the client classes redundant since the namespace already specifies the domain? Should I instead name my classes:

This would mean client code would always use something like:

use Vendor\GoogleClient\Client;

$client = new Client();

This is a little less verbose than:

use Vendor\GoogleClient\GoogleClient;

$client = new GoogleClient();

But the first option allows us to easily swap out implementations by only changing the use statement.

PSR4 specifies that Interfaces and AbstractClasses should be suffixed with Interface and prefixed with Abstract respectively, but it says nothing about domain specific prefixes/suffixes. Any opinions/suggestions?


Solution

  • This is completely up to you as there are no naming conventions for this in PSR. But what you have to keep in mind for your decision is if you decide for

    and you like to use both of them at once (with use)

    use Vendor\GoogleClient\Client;
    use Vendor\GithubClient\Client;
    
    $client = new Client();
    

    you will run into an error because Client is not unique.

    Of course you can still use them at once like

    use Vendor\GoogleClient\Client as GoogleClient;
    use Vendor\GithubClient\Client as GithubClient;
    
    $client1 = new GoogleClient();
    $client2 = new GithubClient();
    

    or without use like

    $client1 = new Vendor\GoogleClient\Client();
    $client2 = new Vendor\GithubClient\Client();
    

    But if you plan that the programmer can switch the client in his code easily with just one line by changing from

    use Vendor\GoogleClient\Client;
    $client = new Client();
    

    to

    use Vendor\GithubClient\Client;
    $client = new Client();
    

    this would be much easier than changing all the new GoogleClient() statements to new GithubClient() too.

    Conclusion
    You see that this decision depends much on your own needs and likings. Decide on your own which one is better for you.