Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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:

  • \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?

like image 254
Anushan Easwaramoorthy Avatar asked Dec 18 '15 16:12

Anushan Easwaramoorthy


2 Answers

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.

like image 126
Pᴇʜ Avatar answered Oct 02 '22 15:10

Pᴇʜ


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.

like image 40
Valerio Bozz Avatar answered Oct 02 '22 14:10

Valerio Bozz