PHP命名空间类命名规范

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

这个比“verbose”少了一些冗长:

use Vendor\GoogleClient\GoogleClient;

$client = new GoogleClient();

但是第一个选项允许我们仅通过更改使用语句来轻松交换实现。

PSR4规定InterfacesAbstractClasses应该分别以InterfaceAbstract为后缀和前缀,但它对特定于域的前缀/后缀没有任何说明。 有任何意见/建议吗?


1
如果PSR没有关于这个的规定,那么这可能取决于个人风格。 - Barmar
2个回答

12

这完全取决于您,因为在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();

这样做比将所有的new GoogleClient()语句更改为new GithubClient()要容易得多。

结论
您可以看到,这个决定很大程度上取决于您自己的需求和喜好。请自行决定哪个更适合您。


我个人更喜欢较短的形式。它更加简洁,迫使开发者更加注意细节。 - laketuna

5
作为一条注释,也要考虑重构使用以下内容:
  • \Vendor\Client\Google
  • \Vendor\Client\GitHub
逻辑是:从最不具体到最具体。
话虽如此,通常情况下这是不可能的。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接