PHP Namespace Class Naming Convention
Asked Answered
R

2

6

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:

  • \Vendor\GoogleClient\GoogleClient
  • \Vendor\GithubClient\GithubClient

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

  • \Vendor\GoogleClient\Client
  • \Vendor\GithubClient\Client

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?

Retractor answered 18/12, 2015 at 16:20 Comment(1)
If the PSR doesn't say anything about this, that presumably leaves it up to individual style.Brandling
L
12

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

  • \Vendor\GoogleClient\Client
  • \Vendor\GithubClient\Client

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.

Lost answered 8/1, 2016 at 9:23 Comment(1)
I personally prefer the shorter form. It's cleaner and forces developers to pay more attention.Mccoy
U
5

As a note, also consider to refactor using:

  • \Vendor\Client\Google
  • \Vendor\Client\GitHub

The logic is: from the less specific to the most one.

Having said that often this is not possible.

Urbanist answered 12/2, 2018 at 21:53 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.