PHP命名空间类命名约定


PHP Namespace Class Naming Convention

我目前遵循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();

这比稍微不那么冗长

use Vendor'GoogleClient'GoogleClient;
$client = new GoogleClient();

但是第一个选项允许我们只需更改use语句就可以轻松地交换实现。

PSR4指定InterfacesAbstractClasses应分别以InterfaceAbstract作为后缀,但它没有提及特定于域的前缀/后缀。有什么意见/建议吗?

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

  • 'Vendor'GoogleClient'Client
  • 'Vendor'GithubClient'Client

并且您喜欢同时使用它们(与use一起)

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

您将遇到一个错误,因为Client不是唯一的。

当然,你仍然可以像一样立即使用它们

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

或没有类似use

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

但是,如果你计划程序员只需从更改一行代码,就可以轻松地切换代码中的客户端

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

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

这将比将所有CCD_ 15语句也更改为CCD_。

结论
你知道这个决定很大程度上取决于你自己的需要和喜好。自己决定哪一个对你更好。

注意,也可以考虑使用进行重构

  • 'Vendor'Client'Google
  • 'Vendor'Client'GitHub

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

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