PHP命名空间类命名约定

Anu*_*thy 3 php naming naming-conventions psr-4 psr-2

我目前正在关注PSR-2和PSR-4.在尝试命名几个课程时,我遇到了一个小困境.这是一个例子.

我有一个基本的REST客户端\Vendor\RestClient\AbstractClient.我有两个这个抽象客户端的实现:

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

由于命名空间已经指定了域,因此客户端类的命名是多余的吗?我应该改为命名我的课程:

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

这意味着客户端代码将始终使用如下内容:

use Vendor\GoogleClient\Client;

$client = new Client();
Run Code Online (Sandbox Code Playgroud)

这比以下更简洁:

use Vendor\GoogleClient\GoogleClient;

$client = new GoogleClient();
Run Code Online (Sandbox Code Playgroud)

但第一个选项允许我们通过仅更改use语句轻松交换实现.

PSR4指定Interfaces并且AbstractClasses应该分别以后缀Interface和前缀为前缀Abstract,但它没有说明域特定的前缀/后缀.有什么意见/建议吗?

Pᴇʜ*_*Pᴇʜ 11

这完全取决于您,因为PSR中没有此命名约定.但是,如果你决定,你必须记住你的决定

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

而且你喜欢一次使用它们(带use)

use Vendor\GoogleClient\Client;
use Vendor\GithubClient\Client;

$client = new Client();
Run Code Online (Sandbox Code Playgroud)

你会遇到一个错误,因为Client它不是唯一的.

当然你仍然可以一次性使用它们

use Vendor\GoogleClient\Client as GoogleClient;
use Vendor\GithubClient\Client as GithubClient;

$client1 = new GoogleClient();
$client2 = new GithubClient();
Run Code Online (Sandbox Code Playgroud)

或者没有use

$client1 = new Vendor\GoogleClient\Client();
$client2 = new Vendor\GithubClient\Client();
Run Code Online (Sandbox Code Playgroud)

但是,如果您计划程序员可以通过更改来轻松地在一行中切换客户端

use Vendor\GoogleClient\Client;
$client = new Client();
Run Code Online (Sandbox Code Playgroud)

use Vendor\GithubClient\Client;
$client = new Client();
Run Code Online (Sandbox Code Playgroud)

这比将所有new GoogleClient()语句更改容易得多new GithubClient().

结论
您看到这个决定很大程度上取决于您自己的需求和喜好.决定你自己哪一个更适合你.


Val*_*ozz 5

请注意,还可以考虑使用以下方法进行重构:

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

逻辑是:从不太具体到最多。

话虽如此,这通常是不可能的。